Understand Session Manager

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:

The last two options are referred to as distributed sessions. Distributed sessions are essential for using HTTP sessions for 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.

Ensure that all of your objects stored in the HttpSession implement the java.io.Serializable interface. This is a best practice for HttpSession development that you should follow because not implementing Serializable can lead to loss of data.

Developing session management in servlets


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionSample extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

		// Step 1: Get the Session object
		boolean create = true;
		HttpSession session = request.getSession(create);

		// Step 2: Get the session data value
		Integer ival = (Integer) session.getAttribute("sessiontest.counter");
		if (ival == null) {
			ival = new Integer(1);
		} else {
			ival = new Integer(ival.intValue() + 1);
		}
		session.setAttribute("sessiontest.counter", ival);

		// Step 3: Output the page
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>Session Tracking Test</title></head>");
		out.println("<body>");
		out.println("<h1>Session Tracking Test</h1>");
		out.println("You have hit this page " + ival + " times" + "<br>");
		out.println("Your " + request.getHeader("Cookie"));
		out.println("</body></html>");
	}
}
					
					

  1. Get the HttpSession object.

    To obtain a session, use the getSession() method of the javax.servlet.http.HttpServletRequest object in the Java Servlet 2.3 API. When you first obtain the HttpSession object, the Session Management facility uses one of three ways to establish tracking of the session: cookies, URL rewriting, or Secure Sockets Layer (SSL) information.

    Assume the Session Management facility uses cookies. In such a case, the Session Management facility creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user (at the same browser) passes the cookie containing the session ID, and the Session Management facility uses this ID to find the user's existing HttpSession object. The servlet specification requires the session management cookie name JSESSIONID.

    In Step 1 of the code sample, the boolean (create) is set to true so that the HttpSession object is created if it does not already exist. (With the Servlet 2.3 API, the javax.servlet.http.HttpServletRequest.getSession() method with no boolean defaults to true and creates a session if one does not already exist for this user).

  2. Store and retrieve user-defined data in the session.

    After a session is established, you can add and retrieve user-defined data to the session. The HttpSession object has methods for adding, retrieving, and removing arbitrary Java objects.

    package javax.servlet.http;
    
    public interface HttpSession {
    
    	public java.lang.Object getAttribute(java.lang.String name);
    	public java.util.Enumeration getAttributeNames();
    	public void removeAttribute(java.lang.String name);
    	public void setAttribute(java.lang.String name, java.lang.Object value);
    
    }
    								

    In Step 2 of the code sample, the servlet reads an Integer Object from the HttpSession, increments it, and writes it back. You can use any name to identify values in the HttpSession object. The code sample uses the name sessiontest.counter.

    Because the HttpSession object is shared among servlets that the user might access, consider adopting a site-wide naming convention to avoid conflicts.

  3. (Optional) Output an HTML response page containing data from the HttpSession object.

  4. Provide feedback to the user that an action has taken place during the session. You may want to pass HTML code to the client browser indicating that an action has occurred.

    For example, in step 3 of the code sample, the servlet generates a Web page that is returned to the user and displays the value of the sessiontest.counter each time the user visits that Web page during the session.

  5. (Optional) Notify Listeners. Objects stored in a session that implement the javax.servlet.http.HttpSessionBindingListener interface are notified when the session is preparing to end and become invalidated. This notice enables you to perform post-session processing, including permanently saving the data changes made during the session to a database.

  6. End the session.

    You can end a session:

    • Automatically with the Session Management facility if a session is inactive for a specified time. The administrators provide a way to specify the amount of time after which to invalidate a session.

    • By coding the servlet to call the invalidate() method on the session object.

    The default timeout period for sessions is defined by the servlet container and can be obtained via the int HttpSession.getMaxInactiveInterval() (sec.) method of the HttpSession interface. This timeout can be changed by the Developer using the HttpSession.setMaxInactiveInterval(int) (sec.) method of the HttpSession interface. The timeout periods used by these methods are defined in SECONDS. By definition, if the timeout period for a session is set to -1 (or ANY NEGATIVE), the session will never expire. The session invalidation will not take effect until all servlets using that session have exited the service method. Once the session invalidation is initiated, a new request must not be able to see that session.

    package javax.servlet.http;
    
    public interface HttpSession {
    
    	public int getMaxInactiveInterval();
    	public void setMaxInactiveInterval(int interval);
    	public void invalidate();
    	public boolean isNew();
    
    }
    								

Enabling URL rewriting or cookies on a server

When you are testing or publishing a Web project to a server, you can use session management to enable URL rewriting or cookies.

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.

To enable URL rewriting or cookies on a server:

  1. In the Server Configuration or Servers view, double-click your WebSphere test environment or server. The server editor opens.

  2. Click the Web tab at the bottom of the editor.

  3. In the Server settings section, select the Enable URL rewriting check box. If URL rewriting is enabled, session tracking uses rewritten URLs to carry the session IDs.

  4. To enable cookies, select the Enable cookies check box. If cookies are enabled, session tracking recognizes session IDs that arrive as cookies and tries to use cookies for sending session IDs.

    Enable cookies

  5. Save your changes and close the editor.

Professional hosting     Belorussian informational portal         Free SCWCD 1.4 Study Guide     Free SCBCD 1.3 Study Guide     Free SCDJWS 1.4 Study Guide     SCDJWS 1.4 Quiz     IBM Test 000-287. Enterprise Application Development with IBM WebSphere Studio, V5.0 Study Guide     Free Mock Exam Engine