HTML Form Processing using Servlets

For : Beginners (Those with basic knowledge on Java Programming)

This tutorial will make you understand how to process a HTML Form using Servlets.  For this to accomplish, we need two files  One HTML file and One Servlet File

Filename: Form.html (Save this file in C:/tomcat/webapps/examples)

<html>
<head>
<title> Form Servlet Demonstration </title>
</head>

<body>
<form method=post action=MSServlet>
Enter your name: <input type="text" name="user"><br>
Enter the Password: <input type="text" name="age"><br>
<input type="submit">
</form>
</body>
</html>

  • The above form is submitted to the MSServlet file which resides in the server or the MSServlet (Server) will provide a response to the Client (Form)
  • The name and age is input by the user and upon submitting the form, the output will be welcoming the user using the name entered in the Text box and also the Age.

File Name : MSServlet.java (Save this file in C:/tomcat/webapps/examples/WEB-INF/classes)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class  MSServlet extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
    {
        res.setContentType("text/html");
        String s1=req.getParameter("user"); //See the name attribute in the Input tag of HTML form
        String s2=req.getParameter("age"); //see the name attribute in the Input Tag of HTML Form
       pw.println("Welcome Mr."+s1);
        pw.println("Your age is."+s2);
    }
}

Compile the file and Make an entry in the web.xml file and run the HTML file using the link http://localhost:8080/examples/form.html

Provide a name and age and click Submit. You can see a page that Welcomes you.

Comments

Popular Posts