添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
热心肠的匕首  ·  Vuetify-nuxt-module · ...·  2 月前    · 
聪明的海龟  ·  Azure Boards 中冲刺 ...·  5 月前    · 
拉风的汉堡包  ·  耶利米書 50:29 ...·  5 月前    · 

// Tutorial //

Session Management in Java - HttpServlet, Cookies, URL Rewriting

Published on August 3, 2022
Default avatar

By Pankaj

Session Management in Java - HttpServlet, Cookies, URL Rewriting

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.

  • Java Web Application Tutorial
  • Java Servlet Tutorial
  • Session Management in Java

    What is a Session?

    Session Management in Java - Cookies

    Session in Java Servlet - HttpSession

    Session Management in Java Servlet - URL Rewriting

    What is a Session?

    Session Management in Java - Cookies

    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="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://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>
    <meta charset="US-ASCII">
    <title>Login Page</title>
    </head>
    <form action="LoginServlet" method="post">
    Username: <input type="text" name="user">
    Password: <input type="password" name="pwd">
    <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" "https://www.w3.org/TR/html4/loose.dtd">
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    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>
    <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

    Session in Java Servlet - HttpSession

    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" "https://www.w3.org/TR/html4/loose.dtd">
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    //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>
    User=<%=user %>
    <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" "https://www.w3.org/TR/html4/loose.dtd">
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    //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>
    <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

    Session Management in Java Servlet - URL Rewriting

    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" "https://www.w3.org/TR/html4/loose.dtd">
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    //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>
    User=<%=user %>
    <!-- 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" "https://www.w3.org/TR/html4/loose.dtd">
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    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>
    <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

    Download Servlet Cookie Example Project

    Download Servlet HttpSession Example Project

    Download Servlet Session URL Rewriting Example Project

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about us


    About the authors
    Default avatar
    Pankaj

    author

    Still looking for an answer?

    Ask a question Search for more help

    Was this helpful?
    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 4, 2021

    if cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case. >> shouldn’t that be “if cookies are disabled, you won’t see jsessionid in the URL…”?

    - abs

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 24, 2020

    Hi Pankaj, Great article! Im working on session management for one my projects. I have one issue regarding the session for subsequent requests. The problem I am facing is I am creating the session in for endpoint in backend and setting a attribute in that session. But when I’m hitting the next subsequent endpoints I am not able to fetch the same session. I can see both session I’d and jsession id in the frontend. But somehow I’m not able to get it in the backend. Having said that the same implementation for login endpoint the session is successfully fetched for subsequent calls. Also when I’m hitting from postman I’m getting the session in the subsequent requests but when I try it from browser it won’t work. Any idea what could I be possibly missing here? Thanks.

    - Chaitresh Naik

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 4, 2020

    excellent article … As i m trying to understand what session is? And thanks for the use case.

    - praneeth

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 7, 2019

    Really very good and useful article

    - Ghulam Murtaza

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    April 13, 2019

    Thanks for this helpful material

    - usman

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 19, 2018

    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!

    - thuong pham

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 2, 2018

    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.

    - suxin

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 16, 2018

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

    - rajesh

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 29, 2017

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

    - Arun SIngh