Servlet Login Example - Session Tracking


Create a session object

Our goal is to store the username and password in our session object as a key value pair. Now as user navigates on our website we can check for the session object.

 HttpSession session = request.getSession();
 session.setAttribute(username, password);

Forward user to the Home Page if username and password matches

  • Create a RequestDispatcher object.
  • RequestDispatecher helps to forward a request from one servlet to another. We will be calling home servlet if credentials gets matched.
RequestDispatcher rd = request.getRequestDispatcher("home");
rd.forward(request, response);

If password doesn't match then show an error message

else{
      out.println("wrong username or password");
} 

Complete Code Example

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author rajat
 */
@WebServlet(urlPatterns = {"/login"})
public class login extends HttpServlet {
    String testusername = "test";
    String testpassword = "test123";

    String name;
    String value;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("user");
        String password = request.getParameter("pass");
        PrintWriter out = response.getWriter();
        if(password.equals(testpassword) && username.equals(testusername)){
            HttpSession session = request.getSession();
            session.setAttribute(username, password);
             RequestDispatcher rd = request.getRequestDispatcher("home");
        rd.forward(request, response);
        }else{
            out.println("wrong username or password");
        }       
     
    }

   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}