What is a Session?

The session is used to identify the user. Let’s understand by a simple example. suppose you are login into any dynamic website. where you get the data as per your profile and another user is login in to the same website and the other user gets data according to his profile. so in background session helps to identify the user.

There are two parties one is Browser and another is Server. when a user login into the application a new session is created into the session pool. This session id is created into the cookies of the browser.

When a user is willing to visit a webpage. first of all, the server checks the authenticity of the user that interaction happens between browser and server. after checking authenticity only the server serve the response to the browser.

Create a Java Web application to manage the session

Now, Let’s create Java web Maven Project, that will contain, index.jsp as a home page and another welcome.jsp to redirect the user, If only login and password are correct else it will redirect to the same index.jsp page.

Most important, Create a servlet (SessionExample.java) that contains the programming logic and code to enable the session and set session attributes.

For Good practice, I recommend destroying the session before creating it. To destroy or invalidate the session we use request.getSession().invalidate();

In case, the session is already enabled it will destroy the existing session, and then we will create the new session.

Now, the Next line will  HttpSession session = request.getSession(true);  to enable the new session and over this session object, we can perform many operations like set Session-Id, Session attribute, and Session interval ETC. we will see all of these settings in the below examples.

index.jsp

Create a JSP file (index.jsp) that contains a simple HTML login form with an Action  action="<%=request.getContextPath()%>/SessionExample" and Post Method method="post"

When a user submits this form, Data(username and password) will be sent to Servlet(SessionExample.java) with the post method.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>

<form action="<%=request.getContextPath()%>/SessionExample" method="post">

UserName: <input type="text" name="uname">

Password: <input type="password" name="password">

<input type="submit" name="uname">

</form>
</body>
</html>

Create a Servlet (SessionExample.java) to Set the session

Now let’s switch to the servlet (SessionExample.java) that contains, programming logics, and code to set the session. In the doPost() method we are getting the username and password from the login form which is available in index.jsp file and then we are using an if-else statement to authenticate the user. if it’s a valid user then we are ready to set a session and the page will be redirected to welcome.jsp otherwise if it’s an invalid user then the page will be redirected to the same login form(index.jsp).

package sessionmgt.controllers;

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;

/**
 * Servlet implementation class SessionExample
 */
@WebServlet("/SessionExample")
public class SessionExample extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionExample() {
        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
  response.getWriter().append("Served at: ").append(request.getContextPath());
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  String name = request.getParameter("uname");
  String password = request.getParameter("password");
  
  if(name.equals("codebun") && password.equals("123")) {
               
   //Invalidate the session
   request.getSession().invalidate();
   HttpSession session = request.getSession(true);
   session.setMaxInactiveInterval(5000);
   response.sendRedirect("welcome.jsp");
   
   
  }else {
   response.sendRedirect("index.jsp");
  }

 }

}

welcome.jsp

Now, If the user is valid and logged in successfully then the user will be redirected to welcome.jsp is a simple HTML page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Welcome</title>
</head>
<body>

Hi login success and session is set
</body>
</html>

pom.xml

Below are the dependencies that will be required to use Servlet to add the required dependencies of the application.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>sessionmgt</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sessionmgt Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
 <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
    
   
    
  </dependencies>
  <build>
    <finalName>sessionmgt</finalName>
  </build>
</project>

Output:

What is Cookies?

A cookie is a small chunk of memory in the browser for a specific browser. chunk is a simple text key (a unique key) that is used to exchange the information between browser and server. Cookies are used to personalize the web experience as they keep track of user performance.

How does the exchange happen in cookies?

In java setCookies() and getCookies() are used to exchange the data or information between browser and server.

If you have run the above example of the session in your browser. A session id is already stored in your browser’s cookies. you can check the browser setting and cookies to get the session id of the URL.

Read and Write operation of cookies using JSP and Servlet

Create an object of Cookie and Add this object with the response, response.addCookie(userCookies);  is used to add or write the cookies t and Cookie[] cookies = request.getCookies();  request.getCookies() method will return an array of cookies.

Let’s continue the above example of session management and Set username as cookies in Servlet “SessionExample.java” and get the username in JSP(welcome.jsp).

Write Cookie in Servlet (SessionExample.java)

package sessionmgt.controllers;

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

/**
 * Servlet implementation class SessionExample
 */
@WebServlet("/SessionExample")
public class SessionExample extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionExample() {
        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
  response.getWriter().append("Served at: ").append(request.getContextPath());
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  String name = request.getParameter("uname");
  String password = request.getParameter("password");
  
  if(name.equals("codebun") && password.equals("123")) {
               
   //Invalidate the session
   request.getSession().invalidate();
   HttpSession session = request.getSession(true);
   session.setMaxInactiveInterval(5000);
   
   Cookie userCookies = new Cookie("name", name);
   response.addCookie(userCookies);
   response.sendRedirect("welcome.jsp");
   
   
  }else {
   response.sendRedirect("index.jsp");
  }

 }

}

Read Cookie in JSP (welcome.jsp)

As we discussed, Cookie will return the array of cookies. now in the welcome.jsp file, Define an array of cookies and get the cookies that are Cookie[] cookies = request.getCookies(); and retrieve the array element using loop as we do in basic programming. To get the exact value of the cookies that name is “name” use cookie.getValue();

<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Welcome</title>
</head>
<body>
hi login success and session is set
<br>
<%
String uName = null;
Cookie[] cookies = request.getCookies();

for(Cookie cookie: cookies ){
 if(cookie != null){
  if(cookie.getName().equals("name")){
   uName = cookie.getValue();
  }	}
}

%>
UserName from Cookies:  <%=uName%>
</body>
</html>

Logout Using Cookies in JSP and Servlet

Below are the major step to perform logout operation using cookies in JSP and Servlet

  1. Add the cookies
  2. Create a logout button and on the button click or submit call the controller(Servlet). that contains the code to destroy the cookies.
  3. Now jump into the Logout servlet and get the current cookies to value, set this value as null, and set the max-age of the cookie as zero.
  4. Now finally add these new attributes into the cookie object.

Create an object of cookie Cookie userCookies = new Cookie("name", name);  with the name as “name” and add this cookie object with a response response.addCookie(userCookies);  If you following the above example then we have already done these lines of code into the servlet ServletExample.java

Cookie userCookies = new Cookie("name", name);
response.addCookie(userCookies);

Create a logut button on welcome.jsp, When the user will click on this logout button then the request will be sent to Servlet(LogoutCtl.java)

<form action="<%=request.getContextPath()%>/LogoutCtl" method="post">
<input type="hidden" name="action" value="logout">
<input type="submit" value="logout">
</form>

Create a servlet LoginCtl.java and Add the below code into doPost() method. where we invalidate the session using request.getSession().invalidate();and get the current cookies to value, set this value as null, and set the max-age of the cookie as zero.

String action = request.getParameter("action");
  if (action.equals("logout")) {
   request.getSession().invalidate();
   Cookie[] cookies = request.getCookies();
   for (Cookie cookie : cookies) {
    if (cookie != null) {

     cookie.setValue(null);
     cookie.setMaxAge(0);
     response.addCookie(cookie);
    }
   }

   response.sendRedirect("index.jsp");

  }

Note: Logout with cookies is not recommended for good practice. instead of cookies user session to perform logout operation.

Logout Using Session in JSP and Servlet

To perform the logout button using the session, We have to enable Session and set attributes after the successful login of the user. In the above example, we use SessionExample.java to enable the session and set an attribute as a name.

HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(5000);
session.setAttribute("name", name);

in the above code, we create a session and set the attribute with the name as “name” Now Get ths Session attribute value in the welcome.jsp file that we just set into the servlet(SessionExample.java).

Keep in mind attribute name to setAttribute(“name”) and getAttribute(“name”) should be same.

String uName = null;

if(request.getSession().getAttribute("name")==null){	
 response.sendRedirect(request.getContextPath()+"/index.jsp");
}else{
 
 uName = request.getSession().getAttribute("name").toString();
}

Now Finally, Destroy the session in LogoutCtl.java servlet. request.getSession().invalidate();is used to destroy the session. now if the session is invalidated or destroyed It means the user is logout successfully.

request.getSession().invalidate();