Skip Headers
Oracle® Containers for J2EE Servlet Developer's Guide
10g Release 3 (10.1.3)
B14426-01
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

4 Understanding and Using Servlet Sessions

Servlet sessions, used to track state information for users over multiple requests and responses, were introduced in "What are Servlet Sessions (User Sessions) Used For?". The following sections provide details and examples, including use of session attributes and cookies:

Overview of Session Tracking

The OC4J servlet container, in compliance with the servlet specification, implements session tracking through HTTP session objects, which are instances of a class that implements the javax.servlet.http.HttpSession interface. (Such a class is provided by the OC4J servlet container.) When a servlet creates an HTTP session object, the client interaction is considered to be stateful.

You can think of a session object as a dictionary that stores values (Java objects) together with their associated keys, or names (Java strings). Each name/value pair constitutes a session attribute.

The following subsections discuss session objects and other session-tracking features:

Session Objects

A servlet uses the getSession() method of the HTTP request object to retrieve or create an HTTP session object. This method takes a boolean argument to specify whether a new session object should be created for the client if one does not already exist within the application. You can use attributes of the session object to store and retrieve data related to the user session, through the setAttribute() and getAttribute() methods. See "Using a Session Object in Your Servlet".

You cannot use session objects to share data between applications, nor can you use them to share data between different clients of the same application. There is one HTTP session object for each client in each application.

Session IDs

In order to maintain a mapping between a particular session and the appropriate session object, so that it can properly access information for the current session, OC4J generates a unique session ID for each session. When a stateful servlet (essentially, a servlet that has created a session object) returns a response to the client, the session ID generated by OC4J is included in the response. If cookies are enabled, OC4J uses a session ID cookie to accomplish this. See "How OC4J Can Use Cookies for Session Tracking".

If cookies are disabled, the session ID is communicated through URL rewriting, and you are required to call the encodeURL() method (or the encodeRedirectURL() method, for includes or forwards) of your HTTP response object. See "Using URL Rewriting for Session Tracking".

Cookies and Persistent Session Data

To make session data persistent, you can store it in a database if you need the protection, transactional safety, and backup features that a database offers. For smaller amounts of data, where database functionality is not required, you can create and use your own cookies, or perhaps use the file system or other remote objects.

A cookie has a name and a single associated value, and is stored as an attribute of the HTTP request and response headers. See "Using Cookies in Your Servlet".

When to Use Cookies Versus Session Attributes

Session data is typically stored and manipulated through attributes of the session object, but for small amounts of data, particularly information that you want to be persistent, you have the option of creating and using cookies instead. When to use cookies instead of session attributes is a matter of preference and intent, but consider the following:

  • Cookies are communicated back and forth between the client and server in the HTTP requests and responses, while a session object remains in the server. It is obviously inefficient to move large amounts of data back and forth between the client and server, so cookies should be used only for small amounts of data.

  • Because cookies travel back and forth over the network or Internet, they are generally less secure than session objects.

One philosophy, for example, might be to use session attributes for business-related data, and cookies for presentation-related data. A cookie can indicate information, such as information about the user, that tells the servlet what to display or how to display it, and does not tend to change between subsequent sessions of the same user.

Using Session Tracking in OC4J

The following sections describe key OC4J features for session tracking:

Configuring Session Tracking and Enabling or Disabling Cookies in OC4J

OC4J performs session tracking according to settings in the <session-tracking> element of the global-web-application.xml or orion-web.xml file.

The servlet container first attempts to accomplish session tracking through cookies. If cookies are disabled, the server can maintain session tracking only through URL rewriting, through the encodeURL() method of the response object, or the encodeRedirectURL() method for forwards or includes. You must include the encodeURL() or encodeRedirectURL() calls in your servlet if cookies may be disabled. See "Using URL Rewriting for Session Tracking".

Cookies are enabled by default, as reflected by the setting cookies="enabled" in <session-tracking>. A setting of cookies="disabled" disables cookies:

<session-tracking cookies="disabled" ... >
   ...
</session-tracking>

Note:

You can explicitly enable or disable cookies through the Application Server Control deployment plan editor sessionTracking property, as discussed in the Oracle Containers for J2EE Deployment Guide.

You can also designate one or more session tracker servlets, according to settings of <session-tracker> subelements of <session-tracking>. Session trackers are useful for logging information, for example. You must define any session trackers in orion-web.xml, not global-web-application.xml, because a <session-tracker> element points to a servlet that is defined within the same application. A session tracker is invoked as soon as a session is created; specifically, at the same time as the invocation of the sessionCreated() method of an HTTP session listener, which is an instance of a class that implements the javax.servlet.http.HttpSessionListener interface. See Chapter 6, "Understanding and Using Event Listeners" for information about session listeners.

Also see "<session-tracking>" and "<session-tracker>".

How OC4J Can Use Cookies for Session Tracking

If cookies are enabled, OC4J uses session tracking cookies as follows:

  1. With the first response to a servlet after a session is created, the servlet container sends a cookie with a session ID back to the client, often along with a small amount of other useful information (all less than 4 KB). The container sends the cookie, named JSESSIONID, in an HTTP Set-Cookie response header.

  2. Upon each subsequent request from the same Web client session, the client sends the cookie back to the server as part of the request, in an HTTP Cookie request header, and the server uses the cookie value to look up session state information to pass to the servlet.

  3. With subsequent responses, the container sends the updated cookie back to the client.

Your servlet code is not required to do anything to send this cookie; the container handles this automatically. Sending cookies back to the server is handled automatically by the Web browser.

Also see "Session Tracking Through Secured Connections".

Using URL Rewriting for Session Tracking

An alternative to cookies is URL rewriting, through the encodeURL() method of the HTTP response object (or, equivalently, the encodeRedirectURL() method for includes or forwards). This mechanism allows OC4J to encode the session ID into a URL path if cookies are disabled. The following conditions must be met:

  • The session must be valid.

  • The session ID has not been received through cookies in previous exchanges with the client.

  • The URL points to a location within the application.

To ensure that the servlet container can use URL rewriting, you must use encodeURL() whenever you write a URL to the output stream, instead of writing the URL directly. For example:

out.println("Click <a href=" + res.encodeURL(req.getRequestURL().toString()) +
            ">this link</a>");
out.println(" to access this page again.<br>");

OC4J uses the parameter jsessionid (in conformance with the servlet specification) to indicate the session ID in the URL path, as in the following example:

http://www.example.com:port/myapp/index.html?jsessionid=6789

The value of the rewritten URL is used by the server to look up session state information to pass to the servlet, which is similar to the functionality of cookies.

To comply with the servlet specification, calls to the encodeURL() and encodeRedirectURL() methods result in no action if cookies are enabled.


Notes:

  • The encodeURL() method replaced the servlet 2.0 encodeUrl() method (note capitalization), which is deprecated.

  • OC4J does not support auto-encoding, in which session IDs are automatically encoded into the URL by the servlet container. This is a nonstandard and resource-intensive process.


Session Tracking Through Secured Connections

When exchanges between OC4J and a client include sensitive information, the transmissions should occur over a secured connection. You can achieve this with HTTPS (transmitting the HTTP protocol over SSL sockets, as discussed in detail in the Oracle Containers for J2EE Security Guide). In this case, cookies or URL rewriting would not be appropriate for transmitting a session ID, given that the ID could be intercepted or spoofed. If the value of the session ID is compromised, the associated session state is vulnerable.

In this secured transmission situation, where HTTPS is used for all transmissions, OC4J stores the information needed to retrieve the session state directly into the SSL connection, as an attribute of the SSL session (functionality that is invisible to the user). This provides the greatest level of security for the session state, but also ties the lifetime of the session state to the lifetime of the SSL connection itself. If the SSL connection is dropped, the session state is lost.

It is also possible for an application to be shared between HTTP and HTTPS. (See "Making an Application Available on HTTP and HTTPS in Standalone OC4J".) If an application is shared in this way, OC4J assumes that transmissions to it may or may not be over the SSL connection. The lack of a guaranteed SSL connection where session information can be stored results in OC4J falling back to cookies or URL rewriting for session tracking, as discussed previously.


Note:

Some older browsers drop the SSL connection in certain circumstances, causing the subsequent and sometimes unexpected loss of session state. If this is a problem, you can work around it by specifying the application as shared to force the use of cookies or URL rewriting for session tracking. This is less secure, but may be the only workable alternative.

Making an Application Available on HTTP and HTTPS in Standalone OC4J

To make a single application available over two protocols in standalone OC4J, that application must be declared in two different Web site XML files, and marked as "shared". This feature is enabled if the shared attribute of the <web-app> element in each Web site XML file is set to "true". Setting an application as shared makes a single application deployment available over the protocols defined for each Web site it is declared within. To share between HTTP and HTTPS, one Web site would be secured, configured for HTTPS, and the other would be not secured, configured for HTTP.

See the Oracle Containers for J2EE Configuration and Administration Guide for additional information about shared applications in OC4J.

Using a Session Object in Your Servlet

This section shows you how to use attributes of a session object, first summarizing key methods of the HttpSession interface, then discussing the creation and retrieval of session attributes through getter and setter methods, and concluding with an example.

Summary of HttpSession Methods

The servlet container uses HTTP session objects—instances of a class provided by OC4J that implements the javax.servlet.http.HttpSession interface—in managing data for user sessions. The HttpSession interface specifies the following public methods to handle session attributes:

  • void setAttribute(String name, Object value)

    Add a session attribute, adding the specified object to the session object, under the specified name.

  • Enumeration getAttributeNames()

    Retrieves a java.util.Enumeration object consisting of String objects for the names of all session attributes.

  • Object getAttribute(String name)

    Retrieves the value of the session attribute that has the specified name (or returns null if there is no match).

  • void removeAttribute(String name)

    Removes the session attribute that has the specified name.

Depending on the configuration of the servlet container and the servlet itself, sessions may expire automatically after a set amount of time. Alternatively, they may be invalidated explicitly by the servlet. Servlets can manage session lifecycle with the following methods, specified in the HttpSession interface:

  • void setMaxInactiveInterval(int interval)

    Set a session timeout interval, in seconds, as an integer, overriding any default in the servlet container or set through the web.xml <session-timeout> element. A negative value indicates no timeout. A value of 0 results in an immediate timeout. Also see "Canceling a Session".

  • int getMaxInactiveInterval()

    Retrieves a value indicating the session timeout interval, in seconds. If you had specified a timeout value through setMaxInactiveInterval(), that is the value that is returned. Otherwise, the value of the web.xml <session-timeout> element is returned, if that was specified. Otherwise, the servlet container default timeout is returned.

  • void invalidate()

    Immediately invalidate the session, unbinding any objects from it.

There are also utility methods to retrieve a servlet context, and to retrieve information about session creation and access:

  • ServletContext getServletContext()

    Retrieves the servlet context that the session belongs to.

  • boolean isNew()

    Returns true within the request that created the session; returns false otherwise.

  • long getCreationTime()

    Returns the time when the session object was created, measured in milliseconds since midnight, January 1, 1970.

  • long getLastAccessedTime()

    Returns the time of the most recent request associated with the client session, measured in milliseconds since midnight, January 1, 1970. If the client session has not yet been accessed, this method returns the session creation time.


Development Tip:

The java.util.Date class has a constructor that takes milliseconds since midnight, January 1, 1970, and converts that value into the date, hours, minutes, and seconds.

For complete information about HttpSession methods, refer to the Sun Microsystems Javadoc for the javax.servlet.http package, at the following location:

http://java.sun.com/j2ee/1.4/docs/api/index.html

Adding and Retrieving Session Attributes

Here are some typical steps in creating and displaying session attributes. These steps are shown in a complete example in "Session Object Example".

  1. Get the session object from the request:

    HttpSession session = request.getSession();
    
    
  2. Take user input to specify each attribute name and value. For this example, assume the servlet has a form that takes the name and value for an attribute and stores them in request parameters called dataname and datavalue. (The form is shown in the complete example.)

    String dataName = request.getParameter("dataname");
    String dataValue = request.getParameter("datavalue");
    
    
  3. Use the specified name and value to set each attribute:

    if (dataName != null && dataValue != null) {
        session.setAttribute(dataName, dataValue);
    }
    
    
  4. If you want to output all the attributes back to the browser, start by calling getAttributeNames() to get all the names:

    Enumeration attributeNames = session.getAttributeNames();
    
    
  5. Iterate through the java.util.Enumeration object to retrieve each name, then retrieve each corresponding value, and output the name and value. In this example, assume all the names and values can be handled as Java strings:

    while (attributeNames.hasMoreElements()) {
       String name = attributeNames.nextElement().toString();
       String value = session.getAttribute(name).toString();
       out.println(name + " = " + value + "<br>");
    }
    

Important:

In a clustered application, any object used as a session attribute must implement the java.io.Serializable interface.


Note:

In the HttpSession interface, the methods setAttribute(), getAttributeNames(), and getAttribute() replace putValue(), getValueNames(), and getValue(), which are deprecated.

Session Object Example

This example puts together the steps in "Adding and Retrieving Session Attributes". There is also code for a form to take user input for attribute names and values, and code to display the session ID, creation time, and last access time (in this case, the time when the last attribute was added).

As in previous examples, the doGet() method is called through the doPost() method, for a POST request.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class SessionExample extends HttpServlet {
    
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
 
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
 
        out.println("<h3>" + "My Session Example" + "</h3>");
 
/* Display session ID, creation time, and access time. */
 
        HttpSession session = request.getSession();
        out.println("Session ID: " + session.getId());
        out.println("<br>");
        out.println("Created: ");
        out.println(new Date(session.getCreationTime()) + "<br>");
        out.println("Last accessed: ");
        out.println(new Date(session.getLastAccessedTime()));
 
/* Set attribute, based on data from user (form is later in code). */
 
        String dataName = request.getParameter("dataname");
        String dataValue = request.getParameter("datavalue");
        if (dataName != null && dataValue != null) {
            session.setAttribute(dataName, dataValue);
        }
 
/* Display all attributes. */
 
        out.println("<P>");
        out.println("The following data is in the session: <br>");
        Enumeration attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
           String name = attributeNames.nextElement().toString();
           String value = session.getAttribute(name).toString();
           out.println(name + " = " + value + "<br>");
        }
 
/* Take user input for an attribute. */
 
        out.println("<P>");
        out.print("<form action=\"");
        out.print("SessionExample\" ");
        out.println("method=POST>");
        out.println("Specify attribute name: ");
        out.println("<input type=text size=20 name=dataname>");
        out.println("<br>");
        out.println("Specify attribute value: ");
        out.println("<input type=text size=20 name=datavalue>");
        out.println("<br><br>");
        out.println("<input type=submit>");
        out.println("</form>");
 
        out.println("</body>");
        out.println("</html>");
        
    }
 
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }
 }

When you first run the servlet, it displays something like the following:

Description of sessnoda.gif follows
Description of the illustration sessnoda.gif

Each time you enter a new attribute name and value and click Submit Query, the output is updated to show the new name/value pair. If you enter "Customer" and "Brian" for one attribute name and its value, and "SSN" and "123-45-6789" for another attribute name and its value, clicking Submit Query after each pair of entries, the output is updated as follows. Note that the last access time of the session object has also changed:

Description of sessdata.gif follows
Description of the illustration sessdata.gif

Using Cookies in Your Servlet

For small amounts of data that are to be persistent, you can create and use your own cookies, assuming cookies are enabled. Cookies are represented by instances of the javax.servlet.http.Cookie class, and are passed between client and server as attributes of the HTTP request and response headers.

A servlet can do the following with cookies:

The following sections provide details, and a complete example, about how to use cookies:


Note:

If cookies are enabled, OC4J automatically uses a cookie in keeping track of your session ID, as discussed in "How OC4J Can Use Cookies for Session Tracking".

Configuring Cookies

Cookies are enabled by default. However, as described in "Configuring Session Tracking and Enabling or Disabling Cookies in OC4J", you can explicitly enable them or disable them by setting cookies="enabled" or cookies="disabled" in the <session-tracking> element of the global-web-application.xml or orion-web.xml file.

The <session-tracking> element has additional cookie settings as well:

  • cookie-domain: This is the desired domain for cookies. In general, this would be used to track a single client or user over multiple Web sites. The setting must start with a period ("."). For example:

    <session-tracking cookie-domain=".us.oracle.com" />
    
    

    In this case, the same cookie is used and reused when the user visits any site that matches the ".us.oracle.com" domain pattern, such as webserv1.us.oracle.com or webserv2.us.oracle.com.

    The domain specification must consist of at least two parts, such as ".us.oracle.com" or ".oracle.com". A setting of ".com", for example, is illegal.

    Cookie domain functionality can be used, for example, to share session state between nodes of a Web application running on different hosts.

    For a particular cookie, you can override the cookie-domain setting through the setDomain() method of the cookie.

  • cookie-max-age: This number is sent with the session cookie and specifies a maximum interval (in seconds) for the browser to save the cookie. By default, the cookie is kept in memory during the browser session and then discarded, so that it is not persistent.

    For a particular cookie, you can override the cookie-max-age setting through the setMaxAge() method of the cookie. See the next section, "Summary of Cookie Methods", for additional information.

Also see "<session-tracking>".


Note:

You can configure cookies through attributes of the sessionTracking property in the Application Server Control deployment plan editor, as discussed in the Oracle Containers for J2EE Deployment Guide.

Summary of Cookie Methods

Use the Cookie constructor to create a new cookie:

  • Cookie(String name, String value)

    Create a cookie with the specified name and value, as Java strings.

Use Cookie getter and setter methods, including the following, to specify or retrieve information about the cookie:

  • String getName()

    Returns the name of the cookie.

  • void setValue(String value)

    Specify a new value for the cookie, as a Java string.

  • String getValue()

    Returns the current value of the cookie, as a Java string.

  • void setDomain(String value)

    By default, cookies are only returned to the server that sent them, but you can use this method to specify a domain, or Domain Name System zone, in which the cookie is visible. See "Configuring Cookies" for information about using cookie domains in OC4J.

  • String getDomain()

    Returns the domain in which the cookie is visible.

  • void setMaxAge(int maxAge)

    Specify a maximum age for the cookie, in seconds, after which it will expire. A value of 0 causes the cookie to be deleted immediately. For a value of -1, the cookie will exist until browser shutdown, so will not be stored persistently. The default is -1, or as otherwise specified in your OC4J configuration. See "Configuring Cookies".

  • int getMaxAge()

    Returns the maximum age of the cookie before expiration, in seconds, or special values as described for setMaxAge().

  • void setComment(String comment)

    Create a comment to provide information about the cookie.

  • String getComment()

    Returns a comment that provides information about the cookie (or null if there is no comment).

For complete information about Cookie methods, refer to the Sun Microsystems Javadoc for the javax.servlet.http package at the following location:

http://java.sun.com/j2ee/1.4/docs/api/index.html

Retrieving, Displaying, and Adding Cookies

Here are some typical steps in creating and displaying cookies. These steps are shown in a complete example in "Cookie Example".

  1. To retrieve an array of javax.servlet.http.Cookie objects containing the current set of cookies in the request, call the getCookies() method of the request object:

    Cookie[] cookies = request.getCookies();
    
    
  2. To output the cookie names and values, iterate through the array (or notify the user if the array is empty):

    if (cookies != null && cookies.length > 0) {
       for (int i = 0; i < cookies.length; i++) {
          Cookie cookie = cookies[i];
          out.print("Cookie name: " + cookie.getName() + "<br>");
          out.println("Cookie value: " + cookie.getValue() + "<br><br>");
       }
    } else {
       out.println("There are no cookies.");
    }
    
    
  3. To create a new cookie, you can take user input to specify the name and value. For this example, assume the servlet has a form that takes the name and value and stores them in request parameters called cookiename and cookievalue. (The form is shown in the complete example.)

    String cookieName = request.getParameter("cookiename");
    String cookieValue = request.getParameter("cookievalue");
    
    
  4. To add the new cookie to the response, first input the specified name and value to the Cookie constructor to create the cookie, then call the addCookie() method of the response object:

    if (cookieName != null && cookieValue != null) {
       Cookie cookie = new Cookie(cookieName, cookieValue);
       response.addCookie(cookie);
    }
    

Cookie Example

This example puts together the steps in "Retrieving, Displaying, and Adding Cookies". There is also code for a form to take user input for cookie names and values.

As in previous examples, the doGet() method is called through the doPost() method, for a POST request.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class CookieExample extends HttpServlet {
    
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
 
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
 
        out.println("<h3>" + "My Cookies Example" + "</h3>");
 
/* Show cookies currently in request. */
 
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            out.println("Your browser is sending the following cookies:<br><br>");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                out.print("Cookie name: " + cookie.getName() + "<br>");
                out.println("Cookie value: " + cookie.getValue() + "<br><br>");
            }
        } else {
            out.println("There are no cookies.");
        }
 
/* Add new cookie that was just specified by user (form code below), and output
   back to the browser to confirm what the user just added.                  */

        String cookieName = request.getParameter("cookiename");
        String cookieValue = request.getParameter("cookievalue");
        if (cookieName != null && cookieValue != null) {
            Cookie cookie = new Cookie(cookieName, cookieValue);
            response.addCookie(cookie);
            out.println("<P>");
            out.println
      ("You just created the following cookie for your browser to send:<br><br>");
            out.print("New cookie name: " + cookieName + "<br>");
            out.print("New cookie value: " + cookieValue + "<br>");
        }

/* Form to prompt user for a cookie name and value. */

        out.println("<P>");
        out.println("Create a new cookie for your browser to send:<br>");
        out.print("<form action=\"");
        out.println("CookieExample\" method=POST>");
        out.print("Specify cookie name: ");
        out.println("<input type=text length=20 name=cookiename><br>");
        out.print("Specify cookie value: ");
        out.println("<input type=text length=20 name=cookievalue><br><br>");
        out.println("<input type=submit></form>");

        out.println("</body>");
        out.println("</html>");
    }
 
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }

}

When you first run the servlet, it outputs the names and values of any cookies that already exist in the request, then prompts you to add a new cookie. In the following sample output, there is already one cookie:

Description of cookie1.gif follows
Description of the illustration cookie1.gif

As soon as you specify a cookie name and value and click Submit Query, the servlet confirms what you entered:

Description of cookie2.gif follows
Description of the illustration cookie2.gif

If you reload the servlet, you will see your new cookie included in the list of cookies currently in the request:

Description of cookie3.gif follows
Description of the illustration cookie3.gif

Canceling a Session

HTTP session objects generally persist for the duration of the server-side session; however, a session can be terminated explicitly by the servlet, or can be canceled by the servlet container after a certain expiration period.

Using a Timeout to Cancel a Session

The default session timeout for the OC4J server is 20 minutes. You can change the default for a specific application by setting the <session-timeout> subelement under the <session-config> element in web.xml. Specify the timeout in minutes, as an integer. For example, to reduce the session timeout to five minutes, add the following lines to the application web.xml file:

<session-config>
  <session-timeout>5</session-timeout>
</session-config>

According to the servlet specification, a negative value specifies the default behavior that a session never times out. For example:

<session-config>
  <session-timeout>-1</session-timeout>
</session-config>

A value of 0 results in an immediate timeout.

To override the OC4J timeout or any <session-timeout> setting, for a particular servlet, you can use the setMaxInactiveInterval() method of the session object. This method is specified in the HttpSession interface. Specify an integer value, but note that with this method, you specify the timeout value in seconds, not minutes. Again, a negative value means there is no timeout.

The following example specifies a timeout of 10 minutes:

HttpSession session = request.getSession();
...
session.setMaxInactiveInterval(600);

The getMaxInactiveInterval() method returns an integer indicating the timeout interval, in seconds. This would be the value set in setMaxInactiveInterval(), if applicable. Otherwise, it would be the value specified in <session-timeout> (converted to seconds), if applicable. If neither setMaxInactiveInterval() nor <session-timeout> has been used, getMaxInactiveInterval() will return the OC4J default timeout value in seconds: 1200.

Explicitly Canceling a Session

A servlet can explicitly cancel a session by invoking the invalidate() method on the session object, as in the following example:

HttpSession session = request.getSession();
...
session.invalidate();

This immediately invalidates the session and unbinds any objects that were bound to it.