| Session Management in JSP |
| |
| Introduction |
| |
| By default, all JSP pages participate in an HTTP session. |
| |
| The HTTP session object can be accessed within scriptlets through the session implicit JSP object. |
| Sessions are a good place for storing beans and objects that need to be shared across other JSP pages and servlets that may be accessed by the user. |
| |
| The session objects is identified by a session ID and stored in the browser as a cookie. If cookies are unsupported by the browser, then the session ID may be maintained by URL rewriting. Support for URL rewriting is not mandated by the JSP specification and is supported only within a few servers. Although we cannot place primitive data types into the session, we can store any valid Java object by identifying it by a unique key. |
| |
| For example: |
<%
Form form = new Form();
session.putValue("form",form);
%> |
| |
| makes available the Form instance within all JSP pages and servlets belonging to the same session. |
| |
| The instance may be retrieved within a different JSP page as: |
<%
Form myForm = (Form) session.getValue("form");
%> |
| |
| The call to session.getValue() returns a reference to the generic Object type. |
| |
| Thus it is important to always cast the value returned to the appropriate data type before using it. It is not mandatory for JSP pages to participate in a session; they may choose to opt out by setting the appropriate attribute of the page directive: |
| <%@ page session="false" %> |
| |
| There is no limit on the number of objects you can store into the session. |
| |
| However, placing large objects into the session may degrade performance, as they take up valuable heap space. By default, most servers set the lifetime of a session object to 30 minutes, although you can easily reset it on a per session basis by invoking setMaxInvalidationInterval(int secs) on the session object. |
| |
| The figure below highlights the general architecture of session management: |
|
| |
| The JSP engine holds a live reference to objects placed into the session as long as the session is valid. If the session is invalidated or encounters a session timeout, then the objects within are flagged for garbage collection. |
| |
| |
|
| |
| |