How to perform login and logout in JSP and Servlet using eclipse

This Java web application development tutorial contains an example of Login and Logout in JSP and servlet using eclipse.

So, Till now we have cover User registration and User login. Now, Let’s see how to add the logout button in the header part and perform the logout operation. Before dive in the project lets under the session in java.

Session in Java

As the name suggests session is an interval or time interval. session plays an important role while working on a java application. But how the session manages the login and logout activity let’s understand this by an example.

When a user login in the application it creates a unique session id and when the user logout from the application that session is destroyed or invalidate.  The unique session will help us to put conditions according to the user type.

How to set session in servlet

HttpSession session=request.getSession(true);
//Set attribute for session
session.setAttribute("session_name", "SessionValue");

How to get session in JSP

session.getAttribute("session_name")

How to destroy or Invalidate session

HttpSession session=request.getSession(false);
session.invalidate();

I hope now you are familiar with the session in java. Now Let’s see how can we implement it in our ongoing Java web application project.

LoginCTL.Java

In doGet() method invalidate() the session and doPost set the session.

package com.javawebapp.Controller;

import java.io.IOException;
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;

import com.javawebapp.beans.UserBeans;
import com.javawebapp.model.UserModel;
import com.javawebapp.utility.DataUtility;
import com.javawebapp.utility.ServletUtility;

/**
 * Servlet implementation class LoginCTL
 */
@WebServlet(name= "LoginCTL", urlPatterns = {"LoginCTL"})
public class LoginCTL extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginCTL() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String op = DataUtility.getString(request.getParameter("operation"));
    HttpSession session=request.getSession(false);
    if("logout".equalsIgnoreCase(op)) {
      session.invalidate();
      ServletUtility.setSuccessMessage("LogoutSucessfully",request);
      
    }
    ServletUtility.forward("jsp/login.jsp", request, response);
    
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
       UserBeans user = new UserBeans();
       String login=request.getParameter("login");
       String pwd=request.getParameter("password");
      
       HttpSession session=request.getSession(true);
       user = UserModel.UserLogin(login,pwd);
       if(user != null) {
      	 session.setAttribute("user", user.getFirstName());
      	 //ServletUtility.setSuccessMessage(request.getParameter("login")+ " is login successfully", request);
      	 ServletUtility.redirect("jsp/welcome.jsp", request, response);
       }else {
      	 ServletUtility.setErrorMessage("Invalid User", request);
      	 ServletUtility.forward("jsp/login.jsp", request, response);
       }
  }

}

Update header.jsp

In header JSP, Get the session and check session is null or not. According to the session will show the menu items.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-secondary">
  <a class="navbar-brand" href="#">Web Application Tutorial</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
    <%if(session.getAttribute("user")== null) {%>
      <li class="nav-item active">
        <a class="nav-link" href="/JavaWebApp/LoginCTL">Login</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/JavaWebApp/RegistrationCTL">Registration</a>
      </li>
      <%} %>
      
      <li class="nav-item">
        <a class="nav-link" href="#">ContactUs</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">AboutUs</a>
      </li>
      <% 
      if(session.getAttribute("user")!= null)
      {%>
    	  <li class="nav-item active">
          <a class="nav-link" href="/JavaWebApp/LoginCTL?operation=logout">Logout</a>
        </li>  
      <%}
      %>
       
    </ul>
  </div>
</nav>

Update welcome.jsp

<%@page import="com.javawebapp.utility.ServletUtility"%>
<body>
<%@ include file="header.jsp"%>
<h3 style="color: green;"><%=ServletUtility.getSuccessMessage(request)%></h3>
<h1>Welcome User <%=session.getAttribute("user")%></h1>
<%@ include file="footer.jsp"%>
</body>
</html>