HTTP session

When a client sends requests from the same browser to the same servlet, the series of requests belong to one session. To know that the requests belong to the same session, the servlet container automatically sends a cookie named JSESSIONID to the client, and this cookie has a long, random, hard-to-guess value (tkojxpz9qk9xo7124pvanc1z as I run the application in Jetty). The servlet maintains a session store that contains the HttpSession instances. The key string that travels in the value of the JSESSIONID cookie identifies the instances. When an HTTP request arrives at the servlet, the container attaches the session to the request object from the store. If there is no session for the key, then one is created, and the code can access the session object by calling the request.getSession() method.

A HttpSession object can store attributes. The program can call the setAttribute(String,Object), getAttribute(String), and removeAttribute(String) methods to store, retrieve, or delete an attribute object. Each attribute is assigned to a String and can be any Object.

Although the session attribute store essentially looks as simple as a Map<String,?> object, it is not. The values stored in the session can be moved from one node to another when the servlet container runs in a clustered or other distributed environment. To do that, the values are serialized; therefore, the values stored in the session should be Serializable. Failing to do so is a very common novice error. During development, executing the code in a simple development Tomcat or Jetty container practically never serializes the session to disk and never loads it from the serialized form. This means that the values set using setAttribute will be available by calling getAttribute. We run into trouble the first time the application gets installed in a clustered environment. As soon as a HTTP request arrives on different nodes getAttribute may return null. The method setAttribute is called on one node and during the processing of the next request getAttribute on a different node cannot deserialize the attribute value from the disk shared among the nodes. This is usually, and sadly, the production environment.

You, as a developer, should also be aware that serializing and de-serializing an object is a heavy operation that costs several CPU cycles. If the structure of the application uses only a part of the client state serving most of the HTTP requests, then this is a waste of CPU to create the whole state in memory from a serialized form and then serializing it again. In such cases, it is more advisable to store only a key in the session and use some database (SQL or NoSQL) or some other service to store the actual data referenced by the key. Enterprise applications almost exclusively use this structure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.108