Previous     Contents     Index     DocHome     Next     
iPlanet Application Server Developer's Guide (Java)



Chapter 11   Creating and Managing User Sessions


This chapter describes how to create and manage a session that allows users and transaction information to persist between interactions.

This chapter contains the following sections:



Introducing Sessions

The term user session refers to a series of user application interactions that are tracked by the server. Sessions are used for maintaining user specific state, including persistent objects (like handles to EJBs or database result sets) and authenticated user identities, among many interactions. For example, a session could be used to track a validated user login followed by a series of directed activities for a particular user.

The session itself resides in the server. For each request, the client transmits the session ID in a cookie or, if the browser does not allow cookies, the server automatically writes the session ID into the URL.

The iPlanet Application Server supports the servlet standard session interface, called HttpSession for all session activities. This interface enables you to write portable, secure servlets.

Additionally, the iPlanet Application Server provides an additional interface, called HttpSession2, which provides support for a servlet security framework, as well as, sharing sessions between servlets and older iPlanet Application Server components (that is, AppLogics).

Behind the scenes, there are two session styles, distributable and local. The main difference between them is that distributable sessions, as the name implies, can be distributed among multiple servers in a cluster, while local sessions are sticky (that is, bound to an individual server). Sticky load balancing is automatically set for application servlets configured to use the local session model. You determine which session style to use in the application configuration file. For more information about session-related elements in the application configuration file, see Chapter 10 "Deployment Packaging."


Sessions and Cookies

A cookie is a small collection of information that can be transmitted to a calling browser and then retrieves it on each subsequent call from the browser so that the server can recognize calls from the same client. A cookie is returned with each call to the site that created it, unless it expires.

Sessions are maintained automatically by a session cookie that is sent to the client when the session is first created. The session cookie contains the session ID, which identifies the client to the browser on each successive interaction. If a client does not support or allow cookies, the server rewrites the URLs where the session ID appears in the URLs from that client.


Sessions and Security

The iPlanet Application Server security model is based on an authenticated user session. Once a session has been created the application user is authenticated (if used) and logged in to the session. Each interaction step from the servlet that receives an EJB request, generates content to a JSP to format the output and is aware the user is properly authenticated.

Additionally, you can specify that a session cookie is only passed on a secured connection (that is, HTTPS), so the session can only remain active on a secure channel.

For more information about security, see Chapter 12 "Writing Secure Applications."



How to Use 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.


Creating or Accessing a Session

To create a new session or to 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 which is encapsulated in the request object. Calling the method with no arguments, creates a session if one does not already exist which is associated with the request. 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 which 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
   }
   else
      // no session, return an error page

   }
}



Note The getSession() method should be called before anything is written to the response stream. Otherwise the SetCookie string is placed in the HTTP response body instead of the HTTP header.



For more information about getSession(), see the Java Servlet Specification v2.2.


Examining Session Properties

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

Table 11-1 shows the methods to examine session properties.


Table 11-1    HttpSession Methods

HttpSession method

Description

getCreationTime()  

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

getId()  

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

getLastAccessedTime()  

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

isNew()  

Returns a Boolean value indicating if the session is new. Its a new session, if the server has created it and the client has not sent a request to it. This 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(currentDate);
   log.println("client has not yet joined session " + mySessionID);
}

Table 11-2 shows the methods to inspect request object properties that relate to the session:


Table 11-2    HttpServletRequest Methods  

HttpServletRequest Methods

Description

getRemoteUser()  

Gets the requesting user name (HTTP authentication can provide the information). Returns null if the request has no user name information.  

getRequestedSessionId()  

Returns the session ID specified with the request. This may 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.  

isRequestedSessionIdValid()  

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

isRequestedSessionIdFromCookie()  

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

isRequestedSessionIdFromURL()  

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 in order to make them persistent across multiple user interactions. The following HttpSession methods provide support for binding objects to the session object:


Table 11-3    HttpSession Methods  

HttpSession Methods

Description

getValue()  

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

getValueNames()  

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

putValue()  

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. Note that the iPlanet Application Server RowSets and JDBC ResultSets are not serializable and cannot be distributed.  

removeValue()  

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 interface automatically notifies the object that it is bound or unbound.


Invalidating a Session

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



Tip The session API does not provide an explicit session logout API, so any logout implementation must call the session.invalidate() API.



 


Invalidating a Session Manually
To invalidate a session manually, simply call the following method:

session.invalidate();

All objects bound to the session are removed.


Setting a Session Timeout
Session timeout is set using the ias-specific Deployment Descriptor. For more information, see the session-info element in Chapter 10 "Deployment Packaging."


Controlling the Session Type

To control the session type set the appropriate elements in the iPlanet Application Server specific XML file. For more information, see the session-info element in Chapter 10 "Deployment Packaging."


Sharing Sessions with AppLogics

Servlet programmers can use the iPlanet Application Server interface, HttpSession2 to share distributable sessions between AppLogics and servlets. Sharing sessions is useful when you want to migrate an application from NAS 2.x to iPlanet Application Server 6.0. HttpSession2 interface adds security and direct distributable sessions manipulation.

Additionally, if you establish a session in an AppLogic using loginSession() and you want to access the session from a servlet, you must call the setSessionVisibility() method in the AppLogic class to instruct the session cookie to transmit to servlets as well as AppLogics. Additionally, this must be completed before calling saveSession().

For example, in an AppLogic:

domain=".mydomain.com";
path="/"; //make entire domain visible
isSecure=true;
if ( setSessionVisibility(domain, path, isSecure) == GXE.SUCCESS )
   { // session is now visible to entire domain }

For more information about setSessionVisibility(), refer to the AppLogic class in the Foundation Class Reference (Java). For more information about sharing sessions between AppLogics and servlets, see the Migration Guide.


Previous     Contents     Index     DocHome     Next     
Copyright © 2001 Sun Microsystems, Inc. Some preexisting portions Copyright © 2001 Netscape Communications Corp. All rights reserved.

Last Updated June 14, 2001