blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

Understanding JSESSIONID


JSESSIONID is a ID generated by Servlet container like Tomcat or Jetty and used for session management in J2EE web application for http protocol.
The ID is sent to the client either within a cookie (default) or as part of the URL (called URLrewriting, used only if cookies are disabled on the browser).


Why a ID?

F5 white paper extract follows,

HTTP (HyperText Transfer Protocol) was designed to support a stateless, requestresponse model of transferring data from a server to a client. Its first version, 1.0, supported a purely 1:1 request to connection ratio (that is, one request-response pair was supported per connection).

Its second version, 1.1, expanded that ratio to be N:1—that is, many requests per connection. This was done in order to address the growing complexity of web pages, including of the many objects and elements that need to be transferred from the server to the client.

Unfortunately, HTTP was not designed to be an application transport protocol. It was designed to transfer documents. Despite the fact that both documents and application protocols are generally text-based, the resemblance ends there. Applications require some way to maintain their state, while documents do not. Applications are built on logical flows and processes, both of which require that the application know where the user is during this time, and that requires state.

HTTP is stateless, so it seems obvious that HTTP would not be appropriate for delivering applications. But it has become the de facto application transport protocol of the web. In what is certainly one of the most widely accepted, useful hacks in technical history, HTTP was given the means by which state could be tracked throughout the use of an application. That “hack” is where sessions and cookies come into play.

Sessions are the way in which web and application servers maintain state.


How JSESSIONID works?

When the first request (that demands a creation of session) arrives on a J2EE server, the server creates HTTPSession object and sends the sessionID to the browser. The browser then send the same sessionId for every subsequent requests.
Thus the stateless protocol becomes a stateful one.

Let's study how it works by experimenting.

Create a dynamic web application project in eclipse.
Create 2 files - index.html and index.jsp


index.jsp


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; UTF-8">
<title>Index</title>
</head>
<body>
JSP Page
</body>
</html>


index.html


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
</head>
<body>
HTML Page
</body>
</html>


web.xml


<?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>Test</display-name>
<welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


After deploying it on tomcat, hit your URL,

http://localhost:8081/Test/index.html

Check the HTTP headers and cookie using your browser debugger/console. Here is my chrome's debugger console.


Note that there is no JSESSION cookie created. In other words the server didn't send a cookie with JSESSIONID set.
This is because the server was not informed to start session management. (because it's a html page)

Now hit

http://localhost:8081/Test/index.jsp

Notice now that the browser received a cookie for the domain localhost which contains a key JSESSIONID.
Also notice the path /Test/.


Once the browser obtains jsessionId it sends it for every request that falls under {domain}/{context} in our case localhost/Test.

The server checks the incoming jsessionId and concludes that it is a HTTP request that belongs to the session identified by that jsessionId.

Try hitting either index.html or index.jsp which shows up the cookie.


There are 2 ways a request(from browser) notifies a container/server to start a new session.
  1. Requesting a jsp page. (as we saw above)
    The container creates certain implicit objects for a JSP and one among those is the HTTPSession object. HTTPSession object holds the sessionId which is written to the response header. You can alter the default behaviour by adding this directive
    <%@ page session="false"%>
  2. Requesting a servlet that has code to initiate the creation by calling,
    request.getSession() - returns a HTTPSession object if it already exists else creates a new one
    request.getSession(true) - same as above
    request.getSession(false) - returns a pre-existing session if it exits else doesn't create one.

Let's try the second case.

Write a servlet and within the same app and deploy.


//Contents of TestServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.getWriter().print("Servlet Response Ends Here");
 response.getWriter().flush();
 response.getWriter().close();
}

Now hitting URL http://localhost:8081/Test/TestServlet does not create HTTPSession.

Update doGet,

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 request.getSession();
 response.getWriter().print("Servlet Response Ends Here");
 response.getWriter().flush();
 response.getWriter().close();
 //request.getSession(); //Cannot create a session after the response has been committed, 
 //will throw java.lang.IllegalStateException 
}

Now if you check, you will notice that the sever sends a JSESSIONID.



How JSESSIONID is generated?

J2EE specification doesn't state how it's to be generated. It's left to the container implementation.
Note that one thing is guaranteed,
A jsessionId is unique within a JVM at a point of time. The same jsessionId might get created again later but not while one already exists within the same JVM.


Why we get the infamous JSP Compilation error: "Duplicate local variable session"?

If you add the below line into a JSP, it will complain Duplicate local variable session

HttpSession session = request.getSession();

This is because when jsp is compiled, implicit objects are created and that includes "session" variable that points to HttpSession.

To handle session creation by yourself in jsp code, use the directive,

<@ page session="false">

Read about

16 comments:

  1. Very nice and informative article !!

    ReplyDelete
  2. does a server see multiple tabs in a browser as one session, or multiple? I guess this is related to how the cookie is assigned, is it a domain cookie or a session cookie? seems it should be a session cookie right? Is there a way to make it a domain cookie?

    ReplyDelete
    Replies
    1. These are the common session cookies

      Delete
    2. If you are trying to share between domains try, http://www.cs-repository.info/2014/04/sharing-jsessionid-across-applications.html

      Delete
  3. very nice article. Thanks for sharing this

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Awesome explanation, it is very helpful. Thanks for sharing this.

    ReplyDelete
  6. Just sooooooooooooooperb......

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Thanks you explained the subject very well.

    ReplyDelete
  9. Java is about language structure and execution when you are coding, yet the genuine excellence of creating lies in the Object Oriented Programming. Solid establishment of OOP will unquestionably make your vocation simple and smooth as a cake. java programming

    ReplyDelete
  10. How we can delet this JessionID If we dont want it ??
    Please help us and Thanks in Advance

    ReplyDelete
    Replies
    1. As far as I know you cannot delete it. It will be created every time by the server even if you are using it or not.

      You could rename it to something else and that is specific to servers. For eg for tomcat: http://stackoverflow.com/questions/877064/changing-cookie-jsessionid-name.

      Have a look here: http://stackoverflow.com/questions/2255814/can-i-turn-off-the-httpsession-in-web-xml

      Delete