Sun Java System Web Server 7.0 Developer's Guide to Java Web Applications

Using Sessions

To use a session, first create a session using the HttpServletRequest method getSession(). Once the session is established, examine and set its properties using the provided methods. If desired, set the session to time out after being inactive for a defined time period, or invalidate it manually. You can also bind objects to the session, which store them for use by other components.

This section includes the following topics:

Creating or Accessing a Session

To create a new session or gain access to an existing session, use the HttpServletRequest method getSession(), as shown in the following example:

HttpSession mySession = request.getSession();

getSession() returns the valid session object associated with the request, identified in the session cookie that is encapsulated in the request object. Calling the method with no arguments creates a session that is associated with the request if one does not already exist. Additionally, calling the method with a Boolean argument creates a session only if the argument is true.

The following example shows the doPost() method from a servlet that only performs the servlet's main functions if the session is present. Note that the false parameter to getSession() prevents the servlet from creating a new session if one does not already exist

public void doPost (HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException
        if ( HttpSession session = req.getSession(false) ) {
           // session retrieved, continue with servlet operations
           // no session, return an error page


Note –

The getSession() method should be called before anything is written to the response stream.

For more information about getSession(), see the Java Servlet 2.4 specification.

Examining Session Properties

Once a session ID has been established, use the methods in the HttpSession interface to examine session properties. Use the methods in the HttpServletRequest interface to examine request properties that relate to the session.

The following table shows the methods used to examine session properties.

Table 6–1 HttpSession Methods

HttpSession Method 



Returns the session time in milliseconds since January 1, 1970, 00:00:00 GMT. 


Returns the assigned session identifier. An HTTP session's identifier is a unique string that is created and maintained by the server. 


Returns the last time the client sent a request carrying the assigned session identifier (or -1 for a new session) in milliseconds since January 1, 1970, 00:00:00 GMT.


Returns a Boolean value indicating that the session is new. A new session is one that the server has created and the client has not sent a request to it. This state means the client has not acknowledged or joined the session and may not return the correct session identification information when making its next request. 

For example:

String mySessionID = mySession.getId();
     if ( mySession.isNew() ) {
        log.println("client has not yet joined session " + mySessionID);


The following table shows the methods used to examine servlet request properties.

Table 6–2 HttpServletRequestMethods

HttpServletRequest Method  



Returns the session ID specified with the request. This value might differ from the session ID in the current session if the session ID given by the client is invalid and a new session was created. Returns null if the request does not have a session associated with it. 


Checks whether the request is associated with a currently valid session. If the session requested is not valid, it is not returned through the getSession() method.


Returns true if the request's session ID provided by the client is a cookie, or false otherwise.


Returns true if the request's session ID provided by the client is a part of a URL, or false otherwise.

For example:

if ( request.isRequestedSessionIdValid() ) {
        if ( request.isRequestedSessionIdFromCookie() ) {
           // this session is maintained in a session cookie
        // any other tasks that require a valid session
      } else {
        // log an application error


Binding Data to a Session

You can bind objects to sessions to make them available across multiple user interactions.

The following table shows the HttpSession methods that provide support for binding objects to the session object.

Table 6–3 HttpSession Methods

HttpSession Method  



Returns the object bound to a given name in the session, or null if there is no such binding. 


Returns an array of names of all attributes bound to the session. 


Binds the specified object into the session with the given name. Any existing binding with the same name is overwritten. For an object bound into the session to be distributed, it must implement the serializable interface. 


Unbinds an object in the session with the given name. If there is no object bound to the given name, this method does nothing. 

Binding Notification with HttpSessionBindingListener

Some objects require you to know when they are placed in or removed from a session. To obtain this information, implement the HttpSessionBindingListener interface in those objects. When your application stores or removes data with the session, the servlet engine checks whether the object being bound or unbound implements HttpSessionBindingListener. If it does, the Sun Java System Web Server 7.0 notifies the object under consideration, through the HttpSessionBindingListener interface, that it is being bound into or unbound from the session.

Invalidating a Session

Direct the session to invalidate itself automatically after being inactive for a defined time period. Alternatively, invalidate the session manually with the HttpSession method invalidate().

Invalidating a Session Manually

To invalidate a session manually, call the following method:


All objects bound to the session are removed.

Setting a Session Timeout

Session timeout is set using the session-timeout element in the web.xml deployment descriptor file. For more information, see the Java Servlet 2.4 specification.