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

Chapter 6 Session Managers

Session objects maintain state and user identity across multiple page requests over the normally stateless HTTP protocol. A session persists for a specified period of time, across more than one connection or page request from the user. A session usually corresponds to one user, who might visit a site many times. The server can maintain a session either by using cookies or by rewriting URLs. Servlets can access the session objects to retrieve state information about the session.

This chapter describes sessions and session managers, and has 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 such as handles to database result sets and authenticated user identities, among many interactions. For example, a session can 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 Web Server supports the servlet standard session interface, called HttpSession, for all session activities.

This section includes the following topics:


Note –

As of Web Server, form-login sessions are no longer supported. You can use single sign-on sessions instead.


Sessions and Cookies

A cookie is a small collection of information that can be transmitted to a calling browser, which 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 server 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.

You can configure whether and how sessions use cookies. For more information on related elements in the sun-web.xml file, see session-properties Element and cookie-properties Element.

Sessions and URL Rewriting

You can also configure whether sessions use URL rewriting. For more information, see the sun-web.xml element session-properties Element.

Sessions and Security

The Web Server security model is based on an authenticated user session. Once a session has been created, the application user is authenticated if authentication is used and is logged into the session.

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

For more information about security, see Chapter 8, Securing 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
        }
        else{
           // 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.5 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 

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 that is created and maintained by the server. 

getLastAccessedTime()

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.

isNew()

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(currentDate);
        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  

Description  

getRequestedSessionId()

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. 

isRequestedSessionIdValid()

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.

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 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  

Description  

getAttribute()

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

getAttributeNames()

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

setAttribute()

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. 

removeAttribute()

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 Web Server 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:

session.invalidate();

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.5 specification.

Session Managers

Web Server provides the following session management options, which are described in this section:

memory Option

The memory is the default memory based session manager.

Enabling memory

You can specify memory explicitly to change its default parameters. To do so, edit the sun-web.xml file for the web application as in the following example. Note that persistence-type must be set to memory.

<sun-web-app>
         ...
        <session-config>
           <session-manager persistence-type=”memory”>
              <manager-properties>
                 <property name="reapIntervalSeconds" value="20" />
              </manager-properties>
           </session-manager>
            ...
        </session-config>
        ...
</sun-web-app>

For more information about the sun-web.xml file, see Chapter 9, Deploying Web Applications.

Manager Properties for Memory

The following table describes manager-properties properties for the memory based session manager.

Table 6–4 manager-properties for memory

Property Name  

Default Value  

Description  

reapIntervalSeconds

60

Specifies the number of seconds between checks for expired sessions. 

Setting this value lower than the frequency at which session data changes is recommended. For example, this value should be as low as possible (1 second) for a hit counter servlet on a frequently accessed web site, or you could lose the last few hits each time you restart the server. 

maxSessions

-1 

Specifies the maximum number of active sessions, or -1 (the default) for no limit.

sessionFilename

SESSIONS

Specifies the absolute or relative path name of the file in which the session state is preserved between application restarts, if preserving the state is possible. A relative path name is relative to the temporary directory for this web application. 

file Session Manager

The file is another file-system-based session manager provided with Web Server. For session persistence, file can use a file to which each session is serialized. You can also create your own persistence mechanism.

Enabling the file Session Manager

You can specify file explicitly to change its default parameters. To do so, edit the sun-web.xml file for the web application as in the following example. Note that persistence-type must be set to file.

<sun-web-app>
        ...
        <session-config>
           <session-manager persistence-type=”file”>
              <manager-properties>
                 <property name=reapIntervalSeconds value=20 />
              </manager-properties>
              <store-properties>
                 <property name=directory value=sessions />
              </store-properties>
           </session-manager>
           ...
        </session-config>
        ...
</sun-web-app>

For more information about the sun-web.xml file, see Chapter 9, Deploying Web Applications.

Manager Properties for file

The following table describes manager-properties properties for the file session manager.

Table 6–5 manager-properties for file

Property Name  

Default Value  

Description  

reapIntervalSeconds

60

Specifies the number of seconds between checks for expired sessions. 

Setting this value lower than the frequency at which session data changes is recommended. For example, this value should be as low as possible (1 second) for a hit counter servlet on a frequently accessed web site, or you could lose the last few hits each time you restart the server. 

maxSessions

-1 

Specifies the maximum number of active sessions, or -1 (the default) for no limit.

IWS60 Session Manager

The IWS60 session manager ensures backward compatibility with any 6.0 session managers that you may have created.

IWS60 works in both single-process and multi-process mode. It can be used for sharing session information across multiple processes possibly running on different machines.


Note –

The MaxProcs directive in the magnus.conf file determines whether the server is running in single-process or multi-process mode. If the value of MaxProcs is higher than 1 and no session manager is configured, then by default the session manager used is the IWS60 with file-based persistence. The Maxprocs is deprecated in Web Server 7.0.


For session persistence, IWS60 can use a database or a distributed file system (DFS) path that is accessible from all servers in a server farm. Each session is serialized to the database or distributed file system. You can also create your own persistence mechanism.

If Web Server is running in single-process mode, then by default, no session persistence mode is defined and therefore sessions are not persistent.

If Web Server is running in multi process mode, sessions are persistent by default. If a persistence mode is not defined, IWS60 uses a DFS.

Multi-process mode is supported only on UNIX platforms. All multi process mode features of IWS60 are ignored on Windows.

Enabling IWS60

You can enable IWS60 to change its default parameters. You can also enable IWS60 for a particular context if the server is running in single-process mode. To do so, edit the sun-web.xml file for the web application as in the following example. The persistence-type must be set to s1ws60.

<sun-web-app>
   ...
   <session-config>
    <session-manager persistence-type=”s1ws60”>
     <manager-properties>
      <property name=”classname” value=”com.iplanet.server.http.
                                       session.IWSSessionManager”/>
      // other manager-related properties
     </manager-properties>
    </session-manager> 
     ...
   </session-config>
   ...
</sun-web-app>

In the case of persistent sessions:

<sun-web-app>
		...
		<session-config/>
		 <session-manager persistence-type=”s1ws60”>
		  <manager-properties>
		   <property name=”classname” value=”com.iplanet.server.http.
                                       session.IWSSessionManager”/>
   	// other manager-related properties
    </manager-properties>
    <store-properties>
     <property name=”classname” value=”com.iplanet.server.http.
                                               session.FileStore”/>
     <property name=”directory” value=”<directory name to store the_
persistant_sessions>”/>
       // other store-related properties
     </store-properties>
    </session-manager> 
   	  ...
   </session-config>
  	 ...
		</sun-web-app>

For more information about the sun-web.xml file, see Chapter 9, Deploying Web Applications.

Manager Properties for IWS60

The following table describes manager-properties properties for the IWS60 session manager.

Table 6–6 manager-properties for IWS60

Property Name  

Default Value  

Description  

maxSessions

1000

The maximum number of sessions maintained by the session manager at any given time. The session manager refuses to create any more new sessions if maxSessions are already number of sessions present at that time.

timeOut

1800

The amount of time in seconds after a session is accessed by the client before the session manager destroys it. Those sessions that are not accessed for at least timeOut seconds are destroyed by the reaper method.

reapInterval

600

The amount of time in seconds that the SessionReaper thread sleeps before calling the reaper method again.

maxLocks

10

The number of cross-process locks to use for synchronizing access to individual sessions across processes. The default value is used if the value 0 is specified. This parameter is ignored in single-process mode.

session-data-store

 

The name of the class that determines the means of session persistence. The classes supplied with Web Server are: 

  • com.iplanet.server.http.session.JdbcStore

  • com.iplanet.server.http.session.FileStore

    If you do not specify the session-data-store parameter, sessions are not persistent in single-process mode, and FileStore is the default in multi-process mode.

    The JdbcStore and FileStore classes are subclasses of the session-data-store class. You can create your own class that implements session persistence by extending SessionDataStore.

session-failover-enabled

 

Specifies whether sessions are reloaded from the persistent store for every request, and always forced to true in multi process mode.

Applicable only if the session-data-store parameter is set to the JdbcStore or FileStore class.

session-data-dir

The following text is single path. 

server_root/server_id/SessionData/virtual_server_id/web_app_URI

The directory in which session data for all servers and web applications is kept. 

Applicable only if the session-data-store parameter is set to the FileStore class.

provider

sun.jdbc.odbc.JdbcOdbcDriver

The JDBC driver. For more information about the JDBC API, see http://java.sun.com/products/jdbc/index.jsp

Applicable only if the session-data-store parameter is set to the JdbcStore class.

url

jdbc:odbc:LocalServer

Specifies the data source. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.

table

sessions

Name of the SQL table that store sessions. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.

username

none 

The login user name for the database. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.

password

none 

The login password for the database. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.

reaperActive

true

When set to true, the session manager runs session reaper to remove expired sessions from the database. The default is true. Only one server in the cluster should run the reaper.

Applicable only if the session-data-store parameter is set to the JdbcStore class.

accessTimeColumn

AccessTime

The name of the column that holds the last access time in minutes. The SQL type is NUMERIC(9).

Applicable only if the session-data-store parameter is set to the JdbcStore class.

timeOutColumn

TimeOut

The name of the column that holds the session timeout in minutes. The SQL type is NUMERIC(9).

Applicable only if the session-data-store parameter is set to the JdbcStore class.

sessionIdColumn

SessionID

The name of the column that holds the session ID. The SQL type is VARCHAR(100).

Applicable only if the session-data-store parameter is set to the JdbcStore class.

valueColumn

Value

The name of the column that holds the session object. The SQL type is VARBINARY(4096). This column must be large enough to accommodate all of your session data.

Applicable only if the session-data-store parameter is set to the JdbcStore class.

lookupPool

4

The number of dedicated connections that perform lookup operations on the database. For higher performance, use a precompiled SQL statement for each of these connections. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.

insertPool

4

The number of dedicated connections that perform insert operations on the database. Each of these connections would have a precompiled SQL statement for higher performance. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.

updatePool

4

The number of dedicated connections that perform update operations on the database. For higher performance, use a precompiled SQL statement for each of these connections. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.

deletePool

2

The number of dedicated connections that perform delete operations on the database. For higher performance, use a precompiled SQL statement for each of these connections. 

Applicable only if the session-data-store parameter is set to the JdbcStore class.


Note –

Prior to using JdbcStore, you must create the table in which the session information is stored. The name of the table is specified by the table parameter, and the table’s four columns are specified by the accessTimeColumn, timeOutColumn, sessionIdColumn, and valueColumn parameters.



Note –

FileStore, JdbcStore, IWSSessionManager, IWSHttpSession, IWSHttpSessionManager, and SessionDataStore have been deprecated in Web Server.


Source Code for IWS60

The IWS60 session manager creates an IWSHttpSession object for each session. The source files for IWSSessionManager.java and IWSHttpSession.java are in the install_dir/lib directory. The source code files for IWSSessionManager.java and IWSHttpSession.java are provided, so you can use them as the starting point for defining your own session managers and session objects.

IWSSessionManager extends IWSHttpSessionManager. The class file for IWSHttpSessionManager is in the JAR file webserv-rt.jar in the directory install_dir/lib. The IWS60 implements all of the methods in IWSHttpSessionManager that need to be implemented, so you can use IWSSessionManager as an example of how to extend IWSHttpSessionManager. When compiling your subclass of IWSSessionManager or IWSHttpSessionManager, be sure that the JAR file webserv-rt.jar is in your compiler’s classpath.

The JdbcStore.java and FileStore.java source files and the source file for the parent class, SessionDataStore.java, are provided so you can modify the session persistence mechanism of IWS60. These files are also located in the install-dir/lib directory.

MMap Session Manager (UNIX Only)

MMap is a persistent memory map (mmap), file-based session manager that works in both single-process and multi-process mode.


Note –

The MaxProcs directive in the magnus.conf file determines whether the server is running in single-process or multi-process mode. The Maxprocs is deprecated in Web Server 7.0.


Enabling MMap

You can enable MMap to change its default parameters. You can also enable MMap for a particular context if the server is running in single-process mode. To do so, edit the sun-web.xml file for the web application as in the following example. Note that persistence-type must be set to mmap.

<sun-web-app>
        ...
        <session-config>
            <session-manager persistence-type=”mmap”>
              ...
          </session-manager>
           ...
        </session-config>
        ...
</sun-web-app>

For more information about the sun-web.xml file, see Chapter 9, Deploying Web Applications.

Manager Properties for MMap

The following table describes manager-properties properties for the MMap session manager.

Table 6–7 manager-properties Properties for MMap

Property Name  

Default Value  

Description  

maxSessions

1000

The maximum number of sessions maintained by the session manager at any given time. The session manager refuses to create any more new sessions if maxSessions number of sessions are already present at that time.

maxValuesPerSession

10

The maximum number of values or objects a session can hold. 

maxValueSize

4096

The maximum size of each value or object that can be stored in the session. 

timeOut

1800

The amount of time in seconds after a session is last accessed by the client before the session manager destroys it. Those sessions that haven’t been accessed for at least timeOut seconds are destroyed by the reaper method.

reapInterval

600

The amount of time in seconds that the SessionReaper thread sleeps before calling the reaper method again.

maxLocks

1

The number of cross-process locks to use for synchronizing access to individual sessions across processes. The default value is used if the value 0 is specified. This parameter is ignored in single-process mode.


Note –

MMap can only store objects that implement java.io.Serializable.