Passing HTML Form Parameters

This is a very simple example in which we are going to display the name on the browser which we have entered from the HTML page. To get the desired result firstly we have to make one “HTML Form” which will have only one field named as name in which we will enter the name. We will also have one submit button, on pressing the submit button the request will go to the Tomcat server and the result will be displayed to us. 

In the servlet which will work as a controller here picks the value from the html page by using the method getParameter().  The output will be displayed to us by the object of the PrintWriter class. The Servlet code named LoginServlet.java is placed under the TestContextParam\src directory.

The code of the program is given below: 

login.html

<html>
<head>
<title>New Page</title>
</head>
<body>
<h2>Login</h2>
<p>Please enter your username and password</p>
<form method="post" action="/HtmlForm/login.do">
  <p> Username  <input type="text" name="username" size="20"></p>
  <p> Password  <input type="password" name="password" size="20"></p>
  <p><input type="submit" value="Submit" name="B1"></p>
</form>
<p>&nbsp;</p>
</body>
</html>

 

LoginServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LoginServlet extends HttpServlet{

public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html>");
out.println("<body>");
out.println("Thanks " + " " + name + " " + "for visiting this web page<br>" );
out.println("Your password is : " + " " + pass + "<br>");
out.println("</body></html>");
}

//for "HTTP GET" method
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

//for "HTTP POST" method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

 

The deployment descriptor (web.xml) is given below:

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
</web-app>

 

The output of the program is given below: 

 

 

 

 

 

 

 

 

On clicking the “Submit” button it will show the following output: