Manage end-user state and understand performance tradeoffs of using HTTP sessions

This page discusses - Manage end-user state and understand performance tradeoffs of using HTTP sessions

Manage end-user state and understand performance tradeoffs of using HTTP sessions

Manage end-user state and understand performance tradeoffs of using HTTP sessions

A session is a series of requests to a servlet, originating from the same user at the same browser.

Sessions allow applications running in a Web container to keep track of individual users.

For example, a servlet might use sessions to provide "shopping carts" to online shoppers. Suppose the servlet is designed to record the items each shopper indicates he or she wants to purchase from the Web site. It is important that the servlet be able to associate incoming requests with particular shoppers. Otherwise, the servlet might mistakenly add Shopper_1's choices to the cart of Shopper_2.

A servlet distinguishes users by their unique session IDs. The session ID arrives with each request. If the user's browser is cookie-enabled, the session ID is stored as a cookie. As an alternative, the session ID can be conveyed to the servlet by URL rewriting, in which the session ID is appended to the URL of the servlet or JavaServer Pages (JSP) file from which the user is making requests. For requests over HTTPS or Secure Sockets Layer (SSL), another alternative is to use SSL information to identify the session.

Session management support

WebSphere Application Server provides facilities, grouped under the heading Session Management, that support the javax.servlet.http.HttpSession interface described in the Servlet API specification.

In accordance with the Servlet 2.3 API specification, the Session management facility supports session scoping by Web module. Only servlets in the same Web module can access the data associated with a particular session. Multiple requests from the same browser, each specifying a unique Web application, result in multiple sessions with a shared session ID. You can invalidate any of the sessions that share a session ID without affecting the other sessions.

You can configure a session timeout for each Web application. A Web application timeout value of 0 (the default value) means that the invalidation timeout value from the Session management facility is used.

When an HTTP client interacts with a servlet, the state information associated with a series of client requests is represented as an HTTP session and identified by a session ID. Session management is responsible for managing HTTP sessions, providing storage for session data, allocating session IDs, and tracking the session ID associated with each client request through the use of cookies or URL rewriting techniques. Session management can store session-related information in several ways:

  • In application server memory (the default). This information cannot be shared with other application servers.

  • In a database. This storage option is known as database persistent sessions.

The last two options are referred to as distributed sessions. Distributed sessions are essential for using HTTP sessions for the failover facility. When an application server receives a request associated with a session ID that it currently does not have in memory, it can obtain the required session state by accessing the external store (database or memory-to-memory). If distributed session support is not enabled, an application server cannot access session information for HTTP requests that are sent to servers other than the one where the session was originally created. Session management implements caching optimizations to minimize the overhead of accessing the external store, especially when consecutive requests are routed to the same application server.

Storing session states in an external store also provides a degree of fault tolerance. If an application server goes offline, the state of its current sessions is still available in the external store. This availability enables other application servers to continue processing subsequent client requests associated with that session.

Saving session states to an external location does not completely guarantee their preservation in case of a server failure. For example, if a server fails while it is modifying the state of a session, some information is lost and subsequent processing using that session can be affected. However, this situation represents a very small period of time when there is a risk of losing session information.

The drawback to saving session states in an external store is that accessing the session state in an external location can use valuable system resources. Session Management can improve system performance by caching the session data at the server level. Multiple consecutive requests that are directed to the same server can find the required state data in the cache, reducing the number of times that the actual session state is accessed in external store and consequently reducing the overhead associated with external location access.

Session tracking options

There are several options for session tracking, depending on what sort of tracking method you want to use:

  • Session tracking with cookies

    Tracking sessions with cookies is the default. No special programming is required to track sessions with cookies.

  • Session tracking with URL rewriting

    An application that uses URL rewriting to track sessions must adhere to certain programming guidelines. The application developer needs to do the following:

    • Program servlets to encode URLs

      Depending on whether the servlet is returning URLs to the browser or redirecting them, include either encodeURL method or encodeRedirectURL method in the servlet code. Examples demonstrating what to replace in your current servlet code follow.

      Suppose you currently have this statement:

      
      out.println("<a href='/store/catalog'>catalog<a>");
      
      											

      Change the servlet to call the encodeURL method before sending the URL to the output stream:

      
      out.println("<a href='");
      out.println(response.encodeURL ("/store/catalog"));
      out.println("'>catalog</a>");
      
      											

      Suppose you currently have the following statement:

      response.sendRedirect ("http://myhost/store/catalog");
      											

      Change the servlet to call the encodeRedirectURL method before sending the URL to the output stream:

      response.sendRedirect (response.encodeRedirectURL ("http://myhost/store/catalog"));
      											

      The encodeURL and encodeRedirectURL methods are part of the HttpServletResponse object. These calls check to see if URL rewriting is configured before encoding the URL. If it is not configured, the calls return the original URL.

      If both cookies and URL rewriting are enabled and the response.encodeURL method or the encodeRedirectURL method is called, the URL is encoded, even if the browser making the HTTP request processed the session cookie.

      You can also configure session support to enable protocol switch rewriting. When this option is enabled, the product encodes the URL with the session ID for switching between HTTP and HTTPS protocols.

    • Supply a servlet or Java Server Pages (JSP) file as an entry point to the application

      The entry point to an application (such as the initial screen presented) may not require the use of sessions. However, if the application in general requires session support (meaning some part of it, such as a servlet, requires session support), then after a session is created, all URLs are encoded to perpetuate the session ID for the servlet (or other application component) requiring the session support.

      The following example shows how you can embed Java code within a JSP file:

      
      <%
      response.encodeURL("/store/catalog");
      %>
      											
      											

    Using URL rewriting also requires that you enable URL rewriting in the session management facility.

    NOTE: In certain cases, clients cannot accept cookies. Therefore, you cannot use cookies as a session tracking mechanism. Applications can use URL rewriting as a substitute. 0

  • Session tracking with SSL information

    No special programming is required to track sessions with Secure Sockets Layer (SSL) information.

    To use SSL information, turn on Enable SSL ID tracking in the session management property page. Because the SSL session ID is negotiated between the Web browser and HTTP server, this ID cannot survive an HTTP server failure. However, the failure of an application server does not affect the SSL session ID if an external HTTP Server is present between WebSphere Application Server and the browser. 1

    SSL tracking is supported for the IBM HTTP Server and iPlanet Web servers only. You can control the lifetime of an SSL session ID by configuring options in the Web server. For example, in the IBM HTTP Server, set the configuration variable SSLV3TIMEOUT to provide an adequate lifetime for the SSL session ID. An interval that is too short can cause a premature termination of a session. Also, some Web browsers might have their own timers that affect the lifetime of the SSL session ID. These Web browsers may not leave the SSL session ID active long enough to serve as a useful mechanism for session tracking. Internal Http Server of WebSphere also supports SSL Tracking.

    When using the SSL session ID as the session tracking mechanism in a cloned environment, use either cookies or URL rewriting to maintain session affinity. The cookie or rewritten URL contains session affinity information that enables the Web server to properly route a session back to the same server for each request.

Best practices for using HTTP Sessions 2

  • Release HttpSession objects using javax.servlet.http.HttpSession.invalidate() method when finished.

    // Get the existing session.
    HttpSession session = request.getSession(false);
    
    if(session != null) {
    	session.invalidate();
    }
    								

    HttpSession objects live inside the Web container until:

    • The application explicitly and programmatically releases it using the javax.servlet.http.HttpSession.invalidate() method; quite often, programmatic invalidation is part of an application logout function. 3

    • WebSphere Application Server destroys the allocated HttpSession when it expires (default = 1800 seconds or 30 minutes). The WebSphere Application Server can only maintain a certain number of HTTP sessions in memory based on session management settings. When this limit is reached, WebSphere Application Server serializes and swaps the allocated HttpSession to disk. In a high volume system, the cost of serializing many abandoned HTTP Sessions can be quite high.

      In case of distributed sessions, when maximum cache limit is reached in memory, the session management facility removes the least recently used (LRU) one from cache to make room for a session.

  • Avoid trying to save and reuse the HttpSession object outside of each servlet or JSP file. 4

    The HttpSession object is a function of the HttpRequest (you can get it only through the req.getSession() method), and a copy of it is valid only for the life of the service method of the servlet or JSP file. You cannot cache the HttpSession object and refer to it outside the scope of a servlet or JSP file.

  • Implement the java.io.Serializable interface when developing new objects to be stored in the HTTP session.

    This action allows the object to properly serialize when using distributed sessions. Without this extension, the object cannot serialize correctly and throws an error. An example of this follows:

    public class MyObject implements java.io.Serializable {
    	...
    }
    								
    Make sure all instance variable objects that are not marked transient are serializable.
  • The HTTP Session API does not dictate transactional behavior for sessions. 5

    Distributed HTTP Session support does not guarantee transactional integrity of an attribute in a failover scenario or when session affinity is broken. Use transactional aware resources like enterprise Java beans to guarantee the transaction integrity required by your application.

  • Avoid storing large object graphs in the HttpSession object.

    In most applications each servlet only requires a fraction of the total session data. However, by storing the data in the HttpSession as one large object, an application forces WebSphere Application Server to process all of it each time. 6

    An HttpSession must be read by the servlet whenever it is used and rewritten whenever it is updated. This involves serializing the data and reading it from and writing it to a database.

  • Do not create HttpSession objects in JSPs by default

    By default, JSP files create HttpSession objects. This is in compliance with J2EE to facilitate the use of JSP implicit objects, which can be referenced in JSP source and tags without explicit declaration. HttpSession is one of those objects. If you do not use HttpSession in your JSP files then you can save some performance overhead with the following JSP page directive:

    
    <%@ page session="false" %>
    
    								

Tutorials

  1. Appendix A. Additional materials
  2. WSAD 5.0 Practicing for IBM Test 000-287 Mind Map
  3. Deploy enterprise applications into servers
  4. Chapter 6. Assemble enterprise applications and deploy them in IBM WebSphere Application Server
  5. Configure resource and security-role references
  6. Design and develop custom tags
  7. Chapter 4. Demonstrate understanding of database connectivity and messaging within IBM WebShpere Application Server
  8. Chapter 5. EJB transactions
  9. Design and develop message-driven EJBs
  10. Design and develop entity EJBs
  11. Validate operational parameters of application server to support the enterprise application
  12. Chapter 1. Design, build and test reusable enterprise components
  13. Access container and server services from enterprise components
  14. Part I. Exam Objectives
  15. Explain implications of resource management on application design and implementation
  16. Manage end-user state and understand performance tradeoffs of using HTTP sessions
  17. Chapter 7. Validate, tune and troubleshoot an application within an IBM WebSphere Application Server environment
  18. Implement mechanisms for efficient inter-component calls
  19. IBM Test 000-287. Enterprise Application Development with IBM WebSphere Studio, V5.0 Study Guide
  20. Chapter 3. Develop clients that access the enterprise components
  21. Implement Java clients calling Web Services
  22. Configure JMS connection factories and destinations
  23. Design, develop and test JSPs
  24. Use JTA to control transaction demarcation
  25. Manipulate transactional behavior of EJBs using deployment descriptors
  26. Implement mechanisms which support loose coupling between clients and components
  27. Identify misbehaving application components
  28. Preface
  29. WSAD 5.0 Practicing for IBM Test 000-287
  30. Part II. Appendixes
  31. Interact with connection pools to obtain and release connections
  32. Describe the effects of a server failure on the application
  33. Test and debug enterprise components
  34. Chapter 2. Design, build and test web components
  35. Chapter 2. Design, build and test web components