Session Management in Java – HttpServlet, Cookies, URL Rewriting

Filed Under: Java EE

Session Management in Java Servlet Web Applications is a very interesting topic. Session in Java Servlet are managed through different ways, such as Cookies, HttpSession API, URL rewriting etc.

Session Management in Java, Session in Java Servlet using Cookies, HttpServlet, URL Rewriting

This is the third article in the series of Web Applications tutorial in Java, you might want to check out earlier two articles too.

  1. Java Web Application Tutorial
  2. Java Servlet Tutorial

Session Management in Java

This article is aimed to explain about session management in servlets using different techniques and with example programs.

  1. What is a Session?
  2. Session Management in Java – Cookies
  3. Session in Java Servlet – HttpSession
  4. Session Management in Java Servlet – URL Rewriting

  1. What is a Session?

    HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new request to process and they can’t identify if it’s coming from client that has been sending request previously.

    But sometimes in web applications, we should know who the client is and process the request accordingly. For example, a shopping cart application should know who is sending the request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount to correct client.

    Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

    There are several ways through which we can provide unique identifier in request and response.

    1. User Authentication – This is the very common way where we user can provide authentication credentials from the login page and then we can pass the authentication information between server and client to maintain the session. This is not very effective method because it wont work if the same user is logged in from different browsers.
    2. HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and keep track of the session. This method can’t be used with links because it needs the form to be submitted every time request is made from client to server with the hidden field. Also it’s not secure because we can get the hidden field value from the HTML source and use it to hack the session.
    3. URL Rewriting – We can append a session identifier parameter with every request and response to keep track of the session. This is very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters.
    4. Cookies – Cookies are small piece of information that is sent by web server in response header and gets stored in the browser cookies. When client make further request, it adds the cookie to the request header and we can utilize it to keep track of the session. We can maintain a session with cookies but if the client disables the cookies, then it won’t work.
    5. Session Management API – Session Management API is built on top of above methods for session tracking. Some of the major disadvantages of all the above methods are:
      • Most of the time we don’t want to only track the session, we have to store some data into the session that we can use in future requests. This will require a lot of effort if we try to implement this.
      • All the above methods are not complete in themselves, all of them won’t work in a particular scenario. So we need a solution that can utilize these methods of session tracking to provide session management in all cases.

      That’s why we need Session Management API and J2EE Servlet technology comes with session management API that we can use.

  2. Session Management in Java – Cookies

    Cookies are used a lot in web applications to personalize response based on your choice or to keep track of session. Before moving forward to the Servlet Session Management API, I would like to show how can we keep track of session with cookies through a small web application.

    We will create a dynamic web application ServletCookieExample with project structure like below image.

    Session in Java using Cookies

    Deployment descriptor web.xml of the web application is:

    
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>ServletCookieExample</display-name>
      <welcome-file-list>
        <welcome-file>login.html</welcome-file>
      </welcome-file-list>
    </web-app>
    

    Welcome page of our application is login.html where we will get authentication details from user.

    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="US-ASCII">
    <title>Login Page</title>
    </head>
    <body>
    
    <form action="LoginServlet" method="post">
    
    Username: <input type="text" name="user">
    <br>
    Password: <input type="password" name="pwd">
    <br>
    <input type="submit" value="Login">
    </form>
    </body>
    </html>
    

    Here is the LoginServlet that takes care of the login request.

    
    package com.journaldev.servlet.session;
    
    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.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String userID = "Pankaj";
    	private final String password = "journaldev";
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		// get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			Cookie loginCookie = new Cookie("user",user);
    			//setting cookie to expiry in 30 mins
    			loginCookie.setMaxAge(30*60);
    			response.addCookie(loginCookie);
    			response.sendRedirect("LoginSuccess.jsp");
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    		}
    
    	}
    
    }
    

    Notice the cookie that we are setting to the response and then forwarding it to LoginSuccess.jsp, this cookie will be used there to track the session. Also notice that cookie timeout is set to 30 minutes. Ideally there should be a complex logic to set the cookie value for session tracking so that it won’t collide with any other request.

    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!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=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    String userName = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    if(userName == null) response.sendRedirect("login.html");
    %>
    <h3>Hi <%=userName %>, Login successful.</h3>
    <br>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    Notice that if we try to access the JSP directly, it will forward us to the login page. When we will click on Logout button, we should make sure that cookie is removed from client browser.

    
    package com.journaldev.servlet.session;
    
    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 LogoutServlet
     */
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        	response.setContentType("text/html");
        	Cookie loginCookie = null;
        	Cookie[] cookies = request.getCookies();
        	if(cookies != null){
        	for(Cookie cookie : cookies){
        		if(cookie.getName().equals("user")){
        			loginCookie = cookie;
        			break;
        		}
        	}
        	}
        	if(loginCookie != null){
        		loginCookie.setMaxAge(0);
            	response.addCookie(loginCookie);
        	}
        	response.sendRedirect("login.html");
        }
    
    }
    

    There is no method to remove the cookie but we can set the maximum age to 0 so that it will be deleted from client browser immediately.

    When we run above application, we get response like below images.

    Session Management in Java using Cookies
    Java Servlet Session Management using Cookies

  3. Session in Java Servlet – HttpSession

    Servlet API provides Session management through HttpSession interface. We can get session from HttpServletRequest object using following methods. HttpSession allows us to set objects as attributes that can be retrieved in future requests.

    1. HttpSession getSession() – This method always returns a HttpSession object. It returns the session object attached with the request, if the request has no session attached, then it creates a new session and return it.
    2. HttpSession getSession(boolean flag) – This method returns HttpSession object if request has session else it returns null.

    Some of the important methods of HttpSession are:

    1. String getId() – Returns a string containing the unique identifier assigned to this session.
    2. Object getAttribute(String name) – Returns the object bound with the specified name in this session, or null if no object is bound under the name. Some other methods to work with Session attributes are getAttributeNames(), removeAttribute(String name) and setAttribute(String name, Object value).
    3. long getCreationTime() – Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. We can get last accessed time with getLastAccessedTime() method.
    4. setMaxInactiveInterval(int interval) – Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. We can get session timeout value from getMaxInactiveInterval() method.
    5. ServletContext getServletContext() – Returns ServletContext object for the application.
    6. boolean isNew() – Returns true if the client does not yet know about the session or if the client chooses not to join the session.
    7. void invalidate() – Invalidates this session then unbinds any objects bound to it.

    Understanding JSESSIONID Cookie

    When we use HttpServletRequest getSession() method and it creates a new request, it creates the new HttpSession object and also add a Cookie to the response object with name JSESSIONID and value as session id. This cookie is used to identify the HttpSession object in further requests from client. If the cookies are disabled at client side and we are using URL rewriting then this method uses the jsessionid value from the request URL to find the corresponding session. JSESSIONID cookie is used for session tracking, so we should not use it for our application purposes to avoid any session related issues.

    Let’s see example of session management using HttpSession object. We will create a dynamic web project in Eclipse with servlet context as ServletHttpSessionExample. The project structure will look like below image.

    HttpSession servlet session management

    login.html is same like earlier example and defined as welcome page for the application in web.xml

    LoginServlet servlet will create the session and set attributes that we can use in other resources or in future requests.

    
    package com.journaldev.servlet.session;
    
    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.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String userID = "admin";
    	private final String password = "password";
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		// get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			HttpSession session = request.getSession();
    			session.setAttribute("user", "Pankaj");
    			//setting session to expiry in 30 mins
    			session.setMaxInactiveInterval(30*60);
    			Cookie userName = new Cookie("user", user);
    			userName.setMaxAge(30*60);
    			response.addCookie(userName);
    			response.sendRedirect("LoginSuccess.jsp");
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    		}
    
    	}
    
    }
    

    Our LoginSuccess.jsp code is given below.

    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!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=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    String user = null;
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }else user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    	if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
    <br>
    User=<%=user %>
    <br>
    <a href="CheckoutPage.jsp">Checkout Page</a>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    When a JSP resource is used, container automatically creates a session for it, so we can’t check if session is null to make sure if user has come through login page, so we are using session attribute to validate request.

    CheckoutPage.jsp is another page and it’s code is given below.

    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!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=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, do the checkout.</h3>
    <br>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    Our LogoutServlet code is given below.

    
    package com.journaldev.servlet.session;
    
    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 LogoutServlet
     */
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        	response.setContentType("text/html");
        	Cookie[] cookies = request.getCookies();
        	if(cookies != null){
        	for(Cookie cookie : cookies){
        		if(cookie.getName().equals("JSESSIONID")){
        			System.out.println("JSESSIONID="+cookie.getValue());
        			break;
        		}
        	}
        	}
        	//invalidate the session if exists
        	HttpSession session = request.getSession(false);
        	System.out.println("User="+session.getAttribute("user"));
        	if(session != null){
        		session.invalidate();
        	}
        	response.sendRedirect("login.html");
        }
    
    }
    

    Notice that I am printing JSESSIONID cookie value in logs, you can check server log where it will be printing the same value as Session Id in LoginSuccess.jsp

    Below images shows the execution of our web application.

    Session in Java Servlet web application

    HttpSession Session in Java Servlet web application

    Session in Java Servlet web application destroy

  4. Session Management in Java Servlet – URL Rewriting

    As we saw in last section that we can manage a session with HttpSession but if we disable the cookies in browser, it won’t work because server will not receive the JSESSIONID cookie from client. Servlet API provides support for URL rewriting that we can use to manage session in this case.

    The best part is that from coding point of view, it’s very easy to use and involves one step – encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled.

    We can encode URL with HttpServletResponse encodeURL() method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL() method.

    We will create a similar project like above except that we will use URL rewriting methods to make sure session management works fine even if cookies are disabled in browser.

    ServletSessionURLRewriting project structure in eclipse looks like below image.

    Session in Java Servlet URL Rewriting

    
    package com.journaldev.servlet.session;
    
    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.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String userID = "admin";
    	private final String password = "password";
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		// get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			HttpSession session = request.getSession();
    			session.setAttribute("user", "Pankaj");
    			//setting session to expiry in 30 mins
    			session.setMaxInactiveInterval(30*60);
    			Cookie userName = new Cookie("user", user);
    			response.addCookie(userName);
    			//Get the encoded URL string
    			String encodedURL = response.encodeRedirectURL("LoginSuccess.jsp");
    			response.sendRedirect(encodedURL);
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    		}
    
    	}
    
    }
    
    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!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=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    String user = null;
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }else user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    	if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
    }
    }else{
    	sessionID = session.getId();
    }
    %>
    <h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
    <br>
    User=<%=user %>
    <br>
    <!-- need to encode all the URLs where we want session information to be passed -->
    <a href="<%=response.encodeURL("CheckoutPage.jsp") %>">Checkout Page</a>
    <form action="<%=response.encodeURL("LogoutServlet") %>" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    
    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!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=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    String userName = null;
    //allow access only if session exists
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }else userName = (String) session.getAttribute("user");
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, do the checkout.</h3>
    <br>
    <form action="<%=response.encodeURL("LogoutServlet") %>" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    
    
    package com.journaldev.servlet.session;
    
    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 LogoutServlet
     */
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        	response.setContentType("text/html");
        	Cookie[] cookies = request.getCookies();
        	if(cookies != null){
        	for(Cookie cookie : cookies){
        		if(cookie.getName().equals("JSESSIONID")){
        			System.out.println("JSESSIONID="+cookie.getValue());
        		}
        		cookie.setMaxAge(0);
        		response.addCookie(cookie);
        	}
        	}
        	//invalidate the session if exists
        	HttpSession session = request.getSession(false);
        	System.out.println("User="+session.getAttribute("user"));
        	if(session != null){
        		session.invalidate();
        	}
        	//no encoding because we have invalidated the session
        	response.sendRedirect("login.html");
        }
    
    }
    

    When we run this project keeping cookies disabled in the browser, below images shows the response pages, notice the jsessionid in URL of browser address bar. Also notice that on LoginSuccess page, user name is null because browser is not sending the cookie send in the last response.

    Session in Java URL Rewriting

    Session Management in Java URL Rewriting

    Session in Java URL Rewriting Logout

    If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.

Thats all for session management in java servlets, we will look into Servlet Filters and Listeners and Cookies in future articles.

Update: Check out next article in the series Servlet Filter.

Download Projects

Comments

  1. usman says:

    Thanks for this helpful material

  2. thuong pham says:

    Hi, Pankaj. Your tutorials are very amazing! Can you tell me how you learn it, which books or documentation that you have read ? thank you so much!

    1. Pankaj says:

      I have been working in Java space for more than 13 years now. Mostly it comes through experience but for starters, go through java books and online video tutorials.

  3. suxin says:

    Can you explain the difference between encodeURL and encodeRedirectURL. In my experiment, encodeRedirectURL in LoginServlet.java will append the session id into URL even if cookies are abled.

  4. rajesh says:

    I am new to session management, but my question is, why we have used Cookie[] ?

    1. Ritesh kumar says:

      Hi, actually we have to use cookies for client interaction and session for only server interaction. Suppose, we have a e-commerce site where we have to add the item in cart there is an client interaction so, we have to use cookies.

  5. Arun SIngh says:

    i was totally unaware of JSESSIONID, you should have explained it better.
    Thanks anyway. great job.

  6. rafhava says:

    main confusion to this article is session.setAttribute(“user”,”pankaj”);
    also cookie=new Cocoike(“user”,user);
    why? both;

    1. Teja says:

      When we use cookie we can just keep track of who the user is by sending it between client and server.

      When we use session we can also store the user data between the requests. For example user stored some items in his cart. This data should be maintained between multiple requests. In this case we can store his cart items in a list and it as session attribute so that we can retrieve cart from session.
      session.setAttribute(“cart”,cartList);
      session.getAttribute(cartList);

      above is my understanding..please do refer to other sources for perfect info.

  7. Jaskaran says:

    Is there any other way of tracking a session in scenarios where cookies are disabled in browser?
    I have a requirement where i don’t want to show jsessionID in the url but still want to continue with the session tracking, Simply put, i want to know about session tracking technique if available other than cookies and Url Rewrtitng.

    Thanks -;)

  8. Devkranth says:

    HI Pankaj

    This holds good for a static page.But how does i go for a Dynamic Page.
    How do i redirect to a page where it will display all the employees still the cookie is active?

  9. Srini says:

    Hi Sir Really thanks for that code, its very helpful.
    i want url base login page that mean , i will type the url and give enter mean that page wants to redirect to next page in between this process i want to do some authentication, that’s , i want’s to get the machine name is client side and check that name in my local table, if the the name match the page redirect else goto login page. local table is Sql table.

  10. Dinesh Kumar says:

    Hi Pankaj,

    Thanks For The Tutorials,,,

    Really Great..

    I have a doubt

    In Cookie Logout,You have added the cookie in response.addcookie(logincookie).

    while logging out .,i shou.ld add or remove cookie?

    1. Shubham says:

      Cookie age is changed to 0. So even if the cookie is added it will expire next moment.

  11. Bülent Akcay says:

    Hi,
    Greate article. I’ve enjoyed to try your Code`s.
    THX

  12. Pritesh says:

    Great job sir.
    You explain it in a way that is very easy to understand.

    I’ve got one problem the images in the tutorial are not loading, I tried alternate browsers,also tried another PC but no luck, please can you help me with this.

  13. Karthik says:

    If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.

    Seems above statement is misspelled can you please check it once ..seems it must be like below , Please correct me if i am wrong

    If cookies are disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.

    1. gerasimius says:

      Pankaj statement is correct.
      If cookies are not disabled then jsessionid is in the cookie and not in URL.

  14. Faiz says:

    Hi,
    Can you please contact me at stereo.heartx@gmail.com ..i got lots of question and need to learn a lots from you…thank you..

  15. jack says:

    hello sir..can i get a idea about how to calculate the time in second between logging in a page and logging out of a page by a user and create a table for that…

  16. vedvrat says:

    1.jsp 2.jsp 3.jsp 4.jsp i have these 4 files.

    1.jsp and 2.jsp have two different forms .. that form data(1.jsp and 2.jsp) are collected in 3.jsp using session …

    In 3.jsp we are Redirect to 4.Jsp …

    So HOW to COLLECT FORM DATA IN 4.JSP USING session ..and I don’t want to use DB for that … please help …??
    Show less

    1. Pankaj says:

      You can use JSP session implicit objects to retrieve the session data and display it.

  17. Alex Blasco says:

    Thank you for sharing this tutorial! It is the best thing that I have found for session’s control. You are a genius.

  18. pradeep says:

    if i check blank condition it doesn’t work

  19. Bhavesh says:

    Hi Pankaj…!

    How to overcome the problem of Back Button…? I mean, if we hit back button on browser it always allow me to get back page again. Could you please give some hint how to implement the solution.

    I’ve tried some solution given by some developers by setting headers, deleting cashes etc but all wastage.
    Please suggest some proper solution for this problem dear.

    Thanks a lot for this article.

  20. Rostislav says:

    Thanks!

  21. somesh says:

    hi pankaj jeee…this tutorial is so use full to me…but i have a small doubt can u please clarifyme…

    i tried “servlethttpsessionexample” it’s working on my system..whenever i login to the page after (30 or 1) minute controller doesn’t go back to login page…i’ve to put one message like (“your session expired please login”) could you plz send me that code as soon as possible…

  22. Asif Mushtaq says:

    Hi Sir, really nice tutorial Amazing, but I have question about SESSION..!!
    why you didn’t removed cookies?

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(“text/html”);
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
    for(Cookie cookie : cookies){
    if(cookie.getName().equals(“JSESSIONID”)){
    System.out.println(“JSESSIONID=”+cookie.getValue());
    break;
    }
    }
    }
    //invalidate the session if exists
    HttpSession session = request.getSession(false);
    System.out.println(“User=”+session.getAttribute(“user”));
    if(session != null){
    session.invalidate();
    }
    response.sendRedirect(“login.html”);
    }

    You just invalidate the session, but not cookies why? it could be a hacking issue?

    1. Ath J says:

      Once the session has been invalidated.The session id for that particular session will not work hence there is no hacking issue

  23. Tanoj kumar sahu says:

    Hi Pankaj,

    what is the best way to maintain session , if you have more than one server maintaining Load Balancer ?

  24. Archita says:

    Hi pankaj, thanx for the this info. i have doubt on the cookie -logoutservlet.java code plz clear it give a explanation to this code.

    public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(“text/html”);
    Cookie loginCookie = null;
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
    for(Cookie cookie : cookies){
    if(cookie.getName().equals(“user”)){
    loginCookie = cookie;
    break;
    }
    }
    }
    if(loginCookie != null){
    loginCookie.setMaxAge(0);
    response.addCookie(loginCookie);
    }
    response.sendRedirect(“login.html”);
    }

    }

  25. caner says:

    Hi Pankaj,
    nice article.By the way,I am wondering why you used both cookies and session in the code “Session Management with HttpSession” section like

    “HttpSession session = request.getSession();
    session.setAttribute(“user”, “Pankaj”);
    //setting session to expiry in 30 mins
    session.setMaxInactiveInterval(30*60);
    Cookie userName = new Cookie(“user”, user);
    userName.setMaxAge(30*60);
    response.addCookie(userName);
    response.sendRedirect(“LoginSuccess.jsp”)”

  26. justin says:

    Hi,

    Nice article indeed.
    Can i check with you what will be the best way for session management if I have two jboss web applications?
    Using jboss 5.1 and struts 1 framework.

    As I require to:
    1) login from 1st web application
    2) when click on one of the module in the 1st web application, able to auto login and access the 2nd web application page.

    I do away with ldap authentication due to time constaint, thus I have research on clustering, session management, but still don’t know which is the easy way out.

    Any advice will be good.

    Thanks.

  27. tarun kumar says:

    I think Url rewriting is unsafe.
    In url rewriting example when loginsuccess.jsp open there session id displaying on url. If i copy url then logout and paste it in address bar and enter that loginsuccess page is open. I want that page should not be open if paste url and session id shouldn’t be dislplay in address bar that anybody can’t copy and illigaly to open page.

  28. Govardhan says:

    Sir You have not configured Servlets in web.xml

    1. Pankaj says:

      Thats because I am using annotations.

  29. Luis Delgado says:

    You sir, are the real MVP. Thank you so much, amazing tutorial!

      1. shashi mahich says:

        Most versatile person (MVP)
        By the way nice tutorials thanks

  30. shams says:

    Good tutorial Sir, looking forward for the future posts.

  31. Ankit says:

    Really very good explanation with good example. Can you please tell me, By default which approach is used to maintain session by a web server like Apache tomcat?

  32. puff says:

    Hatts Off….!

  33. swapnajit says:

    Here is below what i am doing
    while(rs.next()){
    LoadQueueProperties prop = new LoadQueueProperties();
    prop.setGuid(rs.getString(“guid”));
    prop.setHost_name(rs.getString(“host_name”));
    prop.setColl_name(rs.getString(“collection_name”));
    prop.setStage_id(rs.getInt(“stage_id”));
    prop.setClient_name(rs.getString(“client_name”));
    prop.setStatus_code(rs.getInt(“status_code”));

    list.add(prop);
    }
    HttpSession session = request.getSession();
    session.setAttribute(“loadQueueList”, list);

    response.sendRedirect(“LoadQueue.jsp”);

    in the jsp i am donig as below

    ${list.guid}
    ${list.host_name}
    ${list.coll_name}
    ${list.stage_id}
    but loadQueueList is coming as empty

    Any solution?

    1. Nitin Peddewad says:

      To achieve this you need to use following syntax .
      Try this.
      ${sessionScope.loadQueueList.guid}

  34. sud says:

    Hi Sir…
    After logout, I m able to back page. But I want when we press back button it redirect to login page not back to loginsuccess page after logout.

  35. Ashok Korlakunta says:

    Good one

  36. zoyeb says:

    Session Management with HttpSession

    LoginServlet.java Line number 33 session.setAttribute(“user”, “Pankaj”);

    can someone explain why use name pankaj in setAttribute

    1. Nuno Rafael Figueiredo says:

      It’s the hardcode user’s screen-name.

      All values (‘code-name’, ‘password’ and ‘screen-name’) are hard-coded.

    2. Anonymous says:

      Coz computers know Pankaj 😀

  37. Saravanan says:

    Hi,

    I m new to session management. I have a couple of questions.
    1) In Session Management with HttpSession topic above, user name is set on both cookie and session. I don’t understand why do we have to set in both. Why cant we use only session object?
    2) How to maintain the same session for multiple http requests? for example, on page refresh i need to access the value in the previously created session.

    1. Nuno Rafael Figueiredo says:

      1 – HttpSession and cookies are two different session scopes. You MAY want them both. Cookie persist after closing the browser.

      2 – Both session and cookies persist across multiple http requests.

  38. amit says:

    thanks sir …

    for session tutorial ,…….

  39. Chetana says:

    Thanks… it’s nice

  40. rajeswari says:

    thank you so much sir

  41. Roopam says:

    i am working on a web application project………..the problem is that when i deploy then it runs good…………the problem is that when i enter my inside page which must open after login but they open……..so what can i do for this???

  42. Sultan Khan says:

    Hi Sir, i want to remove .jsp extension from url in my java web application.

    I tried servlet mapping tag in web.xml file and i also tried to define my jsp file as servlet in web.xml file but its not working…

    so please give me some solution…

    thanks in advance…

    1. Amit says:

      Start learning struts.. u can do this and many more thing very easily..

  43. farah says:

    Hi
    I was trying Httpsession example but while running it Im getting value as null.Please help

  44. micheal says:

    Thanks for the article
    “If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.”
    i didnt understand this, please elloborate

  45. JS says:

    This examples looks good, but non of your examples work, after I login using admin and password I got a 404 error and import javax.servlet.annotation.WebServlet; and @WebServlet(“/LoginServlet”) give me an error, I try deleting them, I downloaded your examples, and import it in eclipse, I also copied and pasted them, I typed them and the same error 404. I like the definitions and the concepts use, but the example does not work.

    1. Pankaj says:

      Is your servlet container supports Servlet Spec 3? If not you will get these errors, try using Tomcat 7. Also check server logs for exact issue.

      1. canh says:

        Hi Pankaj,
        I have used tomcat 7, but I still get the same error 404. It not call LoginServlet. I checked log, but did not see any logs.
        thanks

  46. Derek Nguyen says:

    I have downloaded your files and tried to run the program in eclipse but whenever I submit the form from the login.html, I got this error: HTTP Status 404 – /practice/LogoutServlet. I have checked that I have all of your files (jsp, html, web, and java) locate in the same folder as yours but it still gives me this error. Please help me.

  47. tushar says:

    sir muze ek system pe kitne log har din me browser pe something search karte hai unka count banana hai to plz give me any suggestions.

  48. rahul says:

    i have one doubt,how much data can store in session and cookies exactly can u tel me briefly

    1. Pankaj says:

      It all depends on the memory for session data, you should keep it small to avoid memory issues.

      You can have many cookies but its value size is limited. Also it will add network overhead because it will be sent from both sides in every request and response, so you should keep it small.

  49. Rebecca says:

    Hi pankaj,
    Thanks a lot. It works..!!.. 🙂 🙂 continue your work..!!

  50. Venkata Sriram says:

    Hi sir,iam having small doubt related to SessionManagement and Servlet Listeners.Question is whenever User is Directly Closing the Browser Window,how do we made session.invalidate() or some changes in database side,how to do sir?please help me Sir.

    1. Pankaj says:

      When user is closing window, you can’t do anything at server side. However we use cookies for session tracking and if you set the cookie to expire as soon as browser is closed, it will invalidate automatically.

      1. Venkata Sriram says:

        Hi sir thanks for reply but iam not using cookies explicitly for session handling sir.by using servletListener Events (HttpSessionEvent) also we cant perform any updation of status or something in database level sir.Correct me if iam wrong.Thanks Venkata Sriram

  51. Saurabh says:

    Sir,
    I have read the tutorial and i want to thnakyou for writing this tutorial.It is really helpful.
    I have a question to ask that how can i disable the back button after the logout button is clicked.
    As for now when i click the back button in the browser then it goes to the LoginSuccess page which we dont want.
    So, how can i prevent that.
    Thanks in advance.

    1. Pankaj says:

      When you click back button, browser uses the cache to load the page. So there is nothing we can do from server side, however we can add javascript code to detect back button usage and forward to login page.

  52. Jiral Dekhtawala says:

    Pankaj Sir,

    as per above example n article its very knowledgeable i want use with database
    can u help me for above example how to use with database
    it my pleasure to if u guide me.. thnks in advance…

  53. Prabhu.g says:

    Hi, I am testing with your code posted above in tutorial it is understanding very clearly..
    but i am getting an 404 error in webpage. (Servlet 3.0 Annotations)

    “message /SessionMgCooki/LoginServlet

    description The requested resource (/SessionMgCooki/LoginServlet) is not available.”

    This is my problem..
    Thanks.

    1. Pankaj says:

      URI is not right, check the configuration for correct URI.

      1. Prabhu.g says:

        Ya sir. I have check the URI. but the same 404 response from server.

  54. Robin says:

    Hi!

    Great tutorial! When i’ve logged in, log out and then goes to the home-page, i get a nullPointerException. Do you know what might be the problem?

  55. tinhvh55 says:

    can you post source code of this tutorial again. i cant get link download above. thanks

  56. HIMANSU NAYAK says:

    Hi Pankaj,
    With the existing session management we also have to make
    the Cookie Secure using setSecure() and Httponly flag.

  57. Anonym says:

    Thanks for the tutorial. It gives a very good understanding and idea of all the various concepts. It always helps me prep for my interviews.

    Thanks again and continue posting and sharing the knowledge.

  58. Murtuza says:

    Very helpful article. It really cleared my basic idea about sessions and cookies.

    I am having really hard time understanding login process using Facebook API specially access token mechanism and logout process. After reading this tutorial, I am sure you will write a great tutorial explaining a simple(if it is!) login-logout process in a Java based web app using Facebook API.

    Thank you for this tutorial.

    1. Aishwarya Singh says:

      Hi Pankaj,
      Thanks for ur tutorial, but i am facing some problem when i am navigating from one server to another in case of URL rewriting(cookie disabled).
      For eg, when coming back to shopping site after making payment at bank site the initial session id is not retained. It’s showing different session id.
      Could u please help me.
      Thanks in advance
      Aishwarya Singh, pune

  59. Nakul says:

    Hi,
    I tried this example.
    After successfully loged in, when i close the browser, and reopen it, my session expires and make me to log in again.
    Can you please tell me that even if we set age of cookie, why the session get expires.
    I should allow me to remain loged in.

  60. Ankur says:

    your tutorial is very good. example are also good. provide some real time example (on authentication, session, logout and others that is used in making site) like we making real time company project. we take care of all these things that is mention above(auth, session etc..) in project. so we can know how it work in real time. like how facebook,twitter session works.

    1. Pankaj says:

      Real life projects are more complex and if I put 10K lines of code here, that will not be a guide or tutorial. You should knows the basics and have the idea of how things work and then build over it based on your requirements.

      1. Sagar Mali says:

        For a newbie it is awesome tutorial to understand how session works. And if we talk about spring and struts f/w’s , they are also using this type of mechanisms in optimized way. Keep it up pankaj…

  61. shahrooh says:

    Pankaj, I always learn new things from your article. Super work !!!

  62. Rahul Kumar says:

    Hi Pankaj,

    My question is from URL Rewriting. Question is, Suppose a session object is created at server side and we use URL Rewriting for maintaining session. After that I close my browser but session object at the server side is still there(not timed out). then again I open the browser goto the history and click on the link in which Jsesionid is attached. I still get acccess to the resource(either cookies enabled or disabled). Even though I copy the link and paste it to another browser then also i access due to publicly supplying jsessionid as url. So i need help how I make website secure while I using URLRewriting…

    1. Pankaj says:

      In that case, you can keep request client IP and browser information in the session attributes and when request arrives, check them in the filter to make sure they match.

    2. andrew says:

      Consider using hidden form fields instead for session tracking. These dont show up in the url

  63. Ricky says:

    Hi Pankaj,

    What happens if the user forgets to logout/closes the browser and login from another browser or machine?
    Is it being handled and how is it handled?

    1. Pankaj says:

      Same browser logins depend on cookies timeout. For different browser and machine, you need to login again because cookies are not there.

  64. Brian Forbes says:

    Thanks very much for the article, this is very thorough and informative. I have two questions if I may. First, you mentioned that by using url encoding, we can manage session data even if cookies are disabled. In the code, you still use cookies though – why is it that it’s possible to use cookies with url encoding ?

    My second question, is it necessary to use Java code in jsp pages to retrieve cookie information ? The data couldn’t be retrieved by e.g. javascript ?

    Thank you

    1. Pankaj says:

      We are still using Cookie because we don’t know if the Client browser accepts Cookies or not. So URL rewriting will come for rescue when cookies are disabled for any browser.

      Regarding retrieving Cookies in JSP pages, we should never use Scriptlets. Since it’s a example, I am using Java code to keep it simple and not overwhelm with lots of information.

      We can use JSP EL cookie implicit object for this. Read more at https://www.journaldev.com/2064/jsp-expression-language-el-example-tutorial

      1. Brian Forbes says:

        Thanks for your reply ! This makes sense. Thanks for the excellent article, very well written and easy to understand.

  65. vajjapelli raju says:

    i want to create session id and that id will stored into a database

  66. David says:

    hi Pankaj, thanks for your tutorial 😀
    but i have problem,in chrome it doesn’t work. pliz help me 🙂

    1. Pankaj says:

      what do you mean that it doesn’t work in Chrome?

    2. jagdish tiwari says:

      Its General.Use Firefox or IE instead.

    3. David says:

      with your tutorial script,in firefox has working. but in chrome the url cannot rewrite session id.
      thanks

  67. Yuga says:

    Hi Pankaj,
    Nice explanation. Keep up the good work.

  68. Vinay Shetty says:

    Your tutorial is very resourceful for beginners like me. If you dont mind can i suggest if you could explain the concepts while using different variable names. For eg. in URL rewriting you have used the variable “user” repeatedly for different purposes to “setattribute”, “cookie request” etc. If you could use different variables like user, uid, usid etc. it would be easier for beginners like me to understand the code in one go.

    Thanks,
    Vinay Shetty

    1. Vinay Shetty says:

      also can you please explain this line.

      ” for(Cookie cookie : cookies) ”

      What does this line do in a for loop? I don’t know about this kind of syntax..

      1. Pankaj says:

        This is the improved for loop where we can traverse through collection or array easily. Its as replacement of

        for(int i=0; i

    2. Pankaj says:

      Hmm makes sense, I will try to keep different variable names going forward.

  69. H S J says:

    I must be missing something, because I don’t understand why you need to store the user’s name in a cookie. Couldn’t this simply be set in the session (session.setAttribute(“user”, user) )?

    Also, isn’t this still vulnerable to a theft of the session ID (i.e., if somebody simply steals my session ID cookie, they will then authenticate as me)?

    Am I correct in thinking that the session data remains stored on the server and is not available on the client?

    Thanks.

    1. Pankaj says:

      HttpSession work on Cookies only and it adds a cookie jsessionid with some random generated value for the session id.

      Please read the post again clearly, cookies can be used for session management but as you stated that if the logic is simple then anyone can hack it. That’s why we should use the Servlet API HttpSession for session management.

  70. deepthi says:

    hi,

    will u please provide some examples to insert login and logout timings into SQL Server database using jsps?

    Thank you

    1. Pankaj says:

      JSPs should not contain business logic, that is a bad programming model. For DB Operations example read this post https://www.journaldev.com/1997/servlet-example-in-java-with-database-connection-and-log4j-integration

  71. James says:

    Thanks Pankaj

    Great way to explain with the output, it really helps the beginner to learn new things.
    Looking forward to some new examples on Springs and other Technology.

  72. jagroop singh says:

    Can you please explain shopping cart using 3-tier architecture in netbeans 7.3.1?

  73. Gowtham says:

    Fantastic Job broo.. keep posting

  74. michael says:

    Thanks for your tutorials. Very well-prepared and explained.

    Look forward to reading your future posts.

    1. Pankaj says:

      Thanks Michael, these positive comments push me in continuing my effort.

  75. indra says:

    Hi,
    the example which you have demonstrated for URLRewriting is not exact.The idea of rewriting is you will append the sessionid which you have set in session.setatttribute along with the response.But you have not done anything like that in URL rewriting.Please clarify.

    1. Pankaj says:

      Hi Indra,

      The concept of URL rewriting is to add the session id in the URLs, servlet response encodeURL and encodeRedirectURL does the same thing for us behind the scene IF cookies are disabled. So basically it’s the same thing where we are using Servlet API for URL rewriting.

  76. naveen says:

    how to maintain session between login and logout if i DO session.invalidate(); for logout page but when i press back button browser at the time show information between login and logout….? plz sir how to stop show information after log-out plz tell me…. i m waiting u response …..

    1. Pankaj says:

      You need to tell browser not to cache the page, you can do this with below code.

      response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
      response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
      response.setDateHeader("Expires", 0); // Proxies.

      If there are several pages, best way to do is create a Filter where you will add these headers in response and configure the filter for all the URIs you don't want to be cached.

  77. Gunnar Boström says:

    Hi,
    Interesting article. I’ve tried it and it does work.
    I thought that it was not possible to set a session attribute and then do a response.sendRedirect
    without loosing the attribute set in the session.
    /Gunnar

    1. Pankaj says:

      It’s because the session is still valid and when client send further requests and we call getSession(), we get the same session and it has the attribute in it.

  78. krishna says:

    i had implemented the example following above steps. coming to this line :

    response.sendRedirect(“LoginSuccess.jsp”);

    i was getting http 404 error .can you please help me.

    1. Pankaj says:

      404 error comes when requested resource is not available, please check if LoginSuccess.jsp is present in the root of your web application.

      Are you deploying directly to Tomcat from Eclipse or you are exporting as WAR file and then deploying it?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages