Skip to main content

Change Tomcat JSESSION Cookie Name and Path


Sometime we have a scenario that two different tomcat application running on same domain,  and you want to share a session cookie in between them, there are two problem will come in this scenario i.e:

1. Session Cookie Name : As both the application have same cookie name i.e JSESSIONID , so its difficult to know which JSESSIONID belongs to which application , so in this scenario we need to change the Session cookie name.

2. Cookie Path : By default tomcat create a session cookie for the app context, due to which we can't share the cookies between two application , so we need to change the cookie path from  context to the root.

For doing the above point we can use ServletContextListener or web.xml file.

1. ServletContextListener


import javax.servlet.SessionCookieConfig;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyTestListener implements ServletContextListener 
{
    public void contextInitialized(ServletContextEvent sce) 
    {
        String comment = "This is my special cookie configuration";
        String domain = "root.com";
        String path = "/";
        boolean isSecure = true;
        boolean httpOnly = false;
        int maxAge = 30000;
        String cookieName = "MY_SESSION";
        SessionCookieConfig scf = sce.getServletContext().getSessionCookieConfig();
        scf.setComment(comment);
        scf.setDomain(domain);
        scf.setHttpOnly(httpOnly);
        scf.setMaxAge(maxAge);
        scf.setPath(path);                // ROOT path
        scf.setSecure(isSecure);
        scf.setName(cookieName); //JSESSION Cookie name

        }
    }
    public void contextDestroyed(ServletContextEvent sce) 
    {
    }
}

2. Web.xml

<session-config>
          <cookie-config> 
                <comment>This is my special cookie configuration</comment> 
                <domain> root.com</domain> 
                <http-only>false</http-only>
                <max-age>30000</max-age> 
                <path>/</path>                      // ROOT path
                <secure>true</secure> 
               <name>MY_SESSION</name> //JSESSION Cookie name
           </cookie-config> 
</session-config>




Comments