Servlet Login Example

This tutorial describes how to create a servlet login form. We will read the posted data and authenticate the user. At the end you will get a complete code example.

Servlet Login Form

Create a html form and add username and password field to it.

<form name="form1" method = 'POST' action = 'login'>
               Username: <input type ="text" name = 'user'><br>
               Password:  <input type ="password" name = 'pass'><br>
               <input type="submit">
  1. We are requesting using POST method which means that the form data will be send in the http request header.
  2. We are requesting login servlet to process our request.

Read form data in a servlet

Whenever we submit our form, it gets submitted using specified method. Here we have specified the POST method. We have a variable "request" that is an instance of HttpServletRequest which helps to get the incoming data. In the following example we extract username and password. There are two ways of doing this:

  1. We read the single form element value using getParameter method. We pass the name of the parameter as an argument.
     String username = request.getParameter("username");
     String password = request.getParameter("password");
  2. Alternatively, we read all parameters from request at once.
     Enumeration pNames = request.getParameterNames();
    getParameterNames() receive all parameters in unspecified order. We can get the name of the parameter and then we fetch its value. We can save the data in hashmap for later access. We traverse through all elements of Enumeration object.
      name = (String) pNames.nextElement();
      value = request.getParameter(name);
      map.put(name, value);

Get the PrintWriter object from response

PrintWriter out = response.getWriter();

Compare username and password

We have hard coded username and password, so we are comparing whether the entered details match or not. So use the code snippet given below as a test data.

String testusername = "test";
String testpassword = "test123";

Later we will use database to fetch the records. But for now use the test strings. Now to initiate the session you need to check for the username and password. If they matches then create a session object.

if(password.equals(testpassword) && username.equals(testusername)){
  //start session