BEA Home | Events | Solutions | Partners | Products | Services | Download | Developer Center | WebSUPPORT
| WebLogic Server Doc Home | Web Applications | Previous Topic | Next Topic | Contents | Index | View as PDF

Using Sessions and Session Persistence in Web Applications

The following sections describe how to set up sessions and session persistence:

- Overview of HTTP Sessions

- Setting Up Session Management

- Configuring Session Persistence

- Using URL Rewriting

Overview of HTTP Sessions

Session tracking enables you to track a user's progress over multiple servlets or HTML pages, which, by nature, are stateless. A session is defined as a series of related browser requests that come from the same client during a certain time period. Session tracking ties together a series of browser requests—think of these requests as pages—that may have some meaning as a whole, such as a shopping cart application.

Setting Up Session Management

WebLogic Server is set up to handle session tracking by default. You need not set any of these properties to use session tracking. However, configuring how WebLogic Server manages sessions is a key part of tuning your application for best performance. Tuning depends upon factors such as:

- How many users you expect to hit the servlet

- How many concurrent users hit the servlet

- How long each session lasts

- How much data you expect to store for each user

- Heap size allocated to the WebLogic Server instance.

HTTP Session Properties

You configure WebLogic Server session tracking with properties in the WebLogic-specific deployment descriptor, weblogic.xml. For instructions on editing the WebLogic-specific deployment descriptor, see Step 4: Define session parameters.

For a complete list of session attributes, see session-descriptor Element.

Session Timeout

You can specify an interval of time after which HTTP sessions expire. When a session expires, all data stored in the session is discarded. You can set the interval in one of two ways:

- Set the TimeoutSecs attribute in the session-descriptor Element of the WebLogic-specific deployment descriptor, weblogic.xml. This value is set in seconds.

- Set the <session-timeout>(see session-config Element) element in the Web Application deployment descriptor, web.xml.

Configuring Session Cookies

WebLogic Server uses cookies for session management when supported by the client browser.

The cookies that WebLogic Server uses to track sessions are set as transient by default and do not outlive the life of the browser. When a user quits the browser, the cookies are lost and the session lifetime is regarded as over. This behavior is in the spirit of session usage and it is recommended that you use sessions in this way.

It is possible to configure many aspects of the cookies used to track sessions with attributes that are defined in the WebLogic-specific deployment descriptor, weblogic.xml. A complete list of session and cookie-related attributes is available session-descriptor Element.

For instructions on editing the WebLogic-specific deployment descriptor, see Step 4: Define session parameters.

Using Longer-Lived Cookies

For longer-lived client-side user data, your application should create and set its own cookies on the browser via the HTTP servlet API, and should not attempt to use the cookies associated with the HTTP session. Your application might use cookies to auto-login a user from a particular machine, in which case you would set a new cookie to last for a long time. Remember that the cookie can only be sent from that client machine. Your application should store data on the server if it must be accessed by the user from multiple locations.

You cannot directly connect the age of a browser cookie with the length of a session. If a cookie expires before its associated session, that session becomes orphaned. If a session expires before its associated cookie, the servlet is not be able to find a session. At that point, a new session is assigned when the request.getSession(true) method is called. You should only make transient use of sessions.

You can set the maximum life of a cookie with the CookieMaxAgeSecs parameter in the session descriptor of the weblogic.xml deployment descriptor. For more information, see Step 4: Define session parameters.

Logging Out and Ending a Session

User authentication information is stored both in the users's session data and in the context of a server or virtual host that is targeted by a Web Application. Using the session.invalidate() method, which is often used to log out a user, only invalidates the current session for a user—the user's authentication information still remains valid and is stored in the context of the server or virtual host. If the server or virtual host is hosting only one Web Application, the session.invalidate() method, in effect, logs out the user.

There are several Java methods and strategies you can use when using authentication with multiple Web Applications. For more information, see Implementing Single Sign-On in the Programming WebLogic HTTP Servlets,.

Configuring Session Persistence

Session Persistence allows the data stored in an HTTP session object to be permanently stored to enable failover and load balancing across a cluster of WebLogic Servers.

There are five different implementations of session persistence:

- Memory (single-server, non-replicated)

- File system persistence

- JDBC persistence

- Cookie-based session persistence

- In-memory replication (across a cluster)

The first four are covered here; in-memory replication is covered in Understanding HTTP Session State Replication.

For file, JDBC, Cookie-based, and in-memory replication, you need to set additional attributes, including PersistentStoreType. Each method has its own set of attributes as shown below.

When your applications stores data in an HTTP session object, the data must be serializable.

Common Properties

You can configure the number of sessions that are held in memory by setting the following properties in the <session-descriptor> element of the WebLogic-specific deployment descriptor, weblogic.xml. These properties are only applicable if you are using session persistence:

  CacheSize

  Limits the number of cached sessions that can be active in memory at any one time. If you are expecting high volumes of simultaneous active sessions, you do not want these sessions to soak up the RAM of your server since this may cause performance problems swapping to and from virtual memory. When the cache is full, the least recently used sessions are stored in the persistent store and recalled automatically when required. If you do not use persistence, this property is ignored, and there is no soft limit to the number of sessions allowed in main memory. By default, the number of cached sessions is 1024. The minimum is 16, and maximum is Integer.MAX_VALUE. An empty session uses less than 100 bytes, but grows as data is added to it.

  SwapIntervalSecs

  The interval the server waits between purging the least recently used sessions from the cache to the persistent store, when the cacheEntries limit has been reached.

  If unset, this property defaults to 10 seconds; minimum is 1 second, and maximum is 604800 (1 week).

  InvalidationIntervalSecs

  Sets the time, in seconds, that WebLogic Server waits between doing house-cleaning checks for timed-out and invalid sessions, and deleting the old sessions and freeing up memory. Set this parameter to a value less than the value set for the <session-timeout> element. Use this parameter to tune WebLogic Server for best performance on high traffic sites.

  The minimum value is every second (1). The maximum value is once a week (604,800 seconds). If unset, the parameter defaults to 60 seconds.

  You set <session-timeout> in the session-config Element of the Web Application deployment descriptor web.xml.

Using Memory-based, Single-server, Non-replicated Persistent Storage

To use memory-based, single-server, non-replicated persistent storage, set the PersistentStoreType property in the <session-descriptor> element of the WebLogic-specific deployment descriptor, weblogic.xml to memory. When you use memory-based storage, all session information is stored in memory and is lost when you stop and restart WebLogic Server.

Note: If you do not allocate sufficient heap size when running WebLogic Server, your server may run out of memory under heavy load.

Using File-based Persistent Storage

For file-based persistent storage for sessions:

1. Set the PersistentStoreType property in the <session-descriptor> element of the WebLogic-specific deployment descriptor, weblogic.xml to file.

2. Set the directory where WebLogic Server stores the sessions. For more information on setting this directory, see PersistentStoreDir.

   If you do not explicitly set a value for this attribute, a temporary directory is created for you by WebLogic Server.

To use file-based persistent storage in a clustered environment (in a WebLogic cluster or in multiple WebLogic instances not in a WebLogic cluster):

- You must explicitly set this attribute to a shared directory that is accessible to all the servers in a cluster. You must create this directory yourself.

- You also need a front-end proxy server to maintain session stickiness. For a given client, the requests should be served by the same server. Otherwise, a problem occurs when multiple servers try to write the same storage.

- You must also set the InvalidationIntervalSecs attribute to a very high value in weblogic.xml.

Using a Database for Persistent Storage (JDBC persistence)

JDBC persistence stores session data in a database table using a schema provided for this purpose. You can use any database for which you have a JDBC driver. You configure database access by using connection pools.

To Configure JDBC-based persistent storage for sessions:

1. Set JDBC as the persistent store method by setting the PersistentStoreType property in the <session-descriptor> element of the WebLogic-specific deployment descriptor, weblogic.xml to jdbc.

2. Set a JDBC connection pool to be used for persistence storage with the PersistentStorePool property of the WebLogic-specific deployment descriptor, weblogic.xml. Use the name of a connection pool that is defined in the WebLogic Server Administration Console.

   For more details on setting up a database connection pool, see Managing JDBC Connectivity.

3. Set an ACL for the connection that corresponds to the users that have permission. For more details on setting up a database connection, see Managing JDBC Connectivity.

4. Set up a database table named wl_servlet_sessions for JDBC-based persistence. The connection pool that connects to the database needs to have read/write access for this table. The following table shows the Column names and data types you should use when creating this table.

   Table 4-1 wl_servlet_sessions table for JDBC-based Persistence

Column name | Type
--- | ---
wl_id | Variable-width alphanumeric column, up to 100 characters; for example, Oracle VARCHAR2(100). The primary key must be set as follows: wl_id + wl_context_path.
wl_context_path | Variable-width alphanumeric column, up to 100 characters; for example, Oracle VARCHAR2(100). This column is used as part of the primary key. (See the wl_id column description.)
wl_is_new | Single char column; for example, Oracle CHAR(1)
wl_create_time | Numeric column, 20 digits; for example, Oracle NUMBER(20)
wl_is_valid | Single char column; for example, Oracle CHAR(1)
wl_session_values | Large binary column; for example, Oracle LONG RAW
wl_access_time | Numeric column, 20 digits; for example, NUMBER(20)
wl_max_inactive_interval | Integer column; for example, Oracle Integer. Number of seconds between client requests before the session is invalidated. A negative time value indicates that the session should never timeout.

If you are using an Oracle DBMS, you can use the following SQL statement to create the wl_servlet_sessions table:

>     create table wl_servlet_sessions
>       ( wl_id VARCHAR2(100) NOT NULL,
>         wl_context_path VARCHAR2(100) NOT NULL,
>         wl_is_new CHAR(1),
>         wl_create_time NUMBER(20),
>         wl_is_valid CHAR(1),
>         wl_session_values LONG RAW,
>         wl_access_time NUMBER(20),
>         wl_max_inactive_interval INTEGER,
>        PRIMARY KEY (wl_id, wl_context_path) );

You can modify the proceeding SQL statement for use with your DBMS.

If you are using SqlServer2000, you can use the following SQL statement to create the wl_servlet_sessions table:

>      create table wl_servlet_sessions
>       ( wl_id VARCHAR2(100) NOT NULL,
>         wl_context_path VARCHAR2(100) NOT NULL,
>         wl_is_new VARCHAR(1),
>         wl_create_time DECIMAL,
>         wl_is_valid VARCHAR(1),
>         wl_session_values IMAGE,
>         wl_access_time DECIMAL,
>         wl_max_inactive_interval INTEGER,
>        PRIMARY KEY (wl_id, wl_context_path) );

You can modify the proceeding SQL statement for use with your DBMS.

Note: You can configure a maximum duration that JDBC session persistence should wait for a JDBC connection from the connection pool before failing to load the session data with the JDBConnectionTimeoutSecs attribute. For more information, see JDBConnectionTimeoutSecs.

Using Cookie-Based Session Persistence

Cookie-based session persistence provides a stateless solution for session persistence by storing all session data in a cookie that is stored in the user's browser. Cookie-based session persistence is most useful when you do not need to store large amounts of data in the session. Cookie-based session persistence can make managing your WebLogic Server installation easier because clustering failover logic is not required. Because the session is stored in the browser, not on the server. You can start and stop WebLogic Servers withcut losing sessions.

When using Cookie-based session persistence, requests are balanced on a per-request basis as opposed to a per-session basis. Balancing on a per-request basis is the correct behaviour, as cookie-based session persistence is completely stateless and it makes no difference as to which server handles the request (data is stored on the client side).

There are some limitations when using cookie-based session persistence:

- You can only store string attributes in the session. If you store any other type of object in the session, an IllegalArgument exception is thrown.

- You cannot flush the HTTP response (because the cookie must be written to the header data before the response is committed).

- If the content length of the response exceeds the buffer size, the response is automatically flushed and the session data cannot be updated in the cookie. (The buffer size is, by default, 8192 bytes. You can change the buffer size with the javax.servlet.ServletResponse.setBufferSize() method.

- You can only use basic (browser-based) authentication.

- Session data is sent to the browser in clear text.

- The user's browser must be configured to accept cookies.

- You cannot use commas (,) in a string when using cookie-based session persistence or an exception occurs.

To set up cookie-based session persistence:

1. Set the PersistentStoreType parameter in the <session-descriptor> element of the WebLogic-specific deployment descriptor, weblogic.xml to cookie.

2. If desired, set a name for the cookie using the PersistentStoreCookieName parameter. The default is WLCOOKIE.

Secure Cookies

As of Service Pack 3, BEA Systems introduced a new parameter that can be used to mark the sessionCookie as secure. If set, the client's browser will only send the cookie back over an HTTPS connection. This ensures that the cookie ID is secure and should only be used on websites that exclusively use HTTPS. Once this feature is enabled, session cookies over HTTP will no longer work; if your client is directed to a non-HTTPS location the session will not be sent. It is highly advisable to turn off URLRewriting if you use this feature; if your application attempts to encode URLs, the session ID will be shared over HTTP. To use this feature, add the following to your weblogic.xml :

>     <session-param>
>     <param-name>CookieSecure</param-name>
>     <param-value>true</param-value>
>     </session-param>
>     <session-param>

As of Service Pack 5, BEA Systems added a new capability to WebLogic Server that allows a user to securely access HTTPS resources in a session that was initiated using HTTP, without loss of session data. For more information on this new feature, see Multiple Web Applications, Cookies, and Authentication.

Using URL Rewriting

In some situations, a browser or wireless device may not accept cookies, which makes session tracking using cookies impossible. URL rewriting is a solution to this situation that can be substituted automatically when WebLogic Server detects that the browser does not accept cookies. URL rewriting involves encoding the session ID into the hyper-links on the Web pages that your servlet sends back to the browser. When the user subsequently clicks these links, WebLogic Server extracts the ID from the URL address and finds the appropriate HttpSession when your servlet calls the getSession() method.

To enable URL rewriting in WebLogic Server, set the URLRewritingEnabled attribute to true. You set the URLRewritingEnabled attribute in the WebLogic-specific deployment descriptor, weblogic.xml, under the <session-descriptor> element. (The default value for this attribute is true.)

Coding Guidelines for URL Rewriting

There are some general guidelines for how your code should handle URLs in order to support URL rewriting.

- Avoid writing a URL straight to the output stream, as shown here:

  >     out.println("<a href=\"/myshop/catalog.jsp\">catalog</a>");

  Instead, use the HttpServletResponse.encodeURL() method, for example:

  >     out.println("<a href=\""
  >          + response.encodeURL("myshop/catalog.jsp")
  >          + "\">catalog</a>");

  Calling the encodeURL() method determines if the URL needs to be rewritten, and if so, it rewrites it by including the session ID in the URL. The session ID is appended to the URL and begins with a semicolon.

- In addition to URLs that are returned as a response to WebLogic Server, also encode URLs that send redirects. For example:

  >     if (session.isNew())
  >       response.sendRedirect
  >     (response.encodeRedirectUrl(welcomeURL));

  WebLogic Server uses URL rewriting when a session is new, even if the browser does accept cookies, because the server cannot tell whether a browser accepts cookies in the first visit of a session.

- Your servlet can determine whether a given session ID was received from a cookie by checking the Boolean returned from the HttpServletRequest.isRequestedSessionIdFromCookie() method. Your application may respond appropriately, or simply rely on URL rewriting by WebLogic Server.

URL Rewriting and Wireless Access Protocol (WAP)

If you are writing a WAP application, you must use URL rewriting because the WAP protocol does not support cookies. In addition, some WAP devices have a 128-character limit on the length of a URL (including parameters), which limits the amount of data that can be transmitted using URL rewriting. To allow more space for parameters, you can limit the size of the session ID that is randomly generated by WebLogic Server by specifying the number of bytes with the IDLength attribute.

You can save additional space by setting the WAP Enabled attribute, which prevents WebLogic Server from sending primary/secondary information with the URL. You set the WAP Enabled attribute by selecting the Server > Configuration > HTTP tabs o f the Administration Console.

Copyright © 2001 BEA Systems, Inc. All rights reserved. Required browser: Netscape 4.0 or higher, or Microsoft Internet Explorer 4.0 or higher.