Maintain Session using Cookies in jsp servlet

Session can be maintained using browser cookies.
Here in this post, we will see how to Maintain Session using Cookies in JSP servlet.

It is very simple to maintain session using cookies, you just need to create an object of Cookie Class then call addCookie() method on response.

Code Snippet:

Cookie user_defined_cookie = new Cookie("user_defied_cookie",
"You clicked on 'cookies' link.");
// Add cookie in the response header.
response.addCookie(user_defined_cookie);

 
See full example below:

—index.jsp—







How to maintain Session?

How to maintain Session?



1. Cookies

 

—Cookie.java—

package com.java;

import java.io.IOException;

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;

@WebServlet(name = "Cookie Servlet", description = "This is a Cookie servlet", urlPatterns = "/cookie")
public class Cookies extends HttpServlet {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		System.out.println("Session using cookies");
		Cookie user_defined_cookie = new Cookie("user_defied_cookie",
				"You clicked on 'cookies' link.");

		// Add cookie in the response header.
		response.addCookie(user_defined_cookie);

		// Set response content type
		response.setContentType("text/html");

		response.sendRedirect("cookies/cookie.jsp");
	}
}

 
—cookie.jsp—







Cookies
	user_defined_cookie:
	


 

Explanation:
Once you run the code, you will see a cookie has been created with name “JSESSIONID”. This JSESSIONID is assigned by the apache tomcat server to the client or browser.
Expiration of this JSESSIONID can be configured in web.xml file.
 
cookies1

 
A cookie will be set, when you click on the ‘Cookies’ link. You can give any name to the link, Apple, for example.
This cookie is created using the code above.

 
cookie2