Database Reference
In-Depth Information
The servlet and JSP session interface
Tomcat uses the standard session interface described in the Java Servlet Specification.
This interface can be used both by servlets and by JSP pages. Within a servlet, access
the session by importing the javax.servlet.http.HttpSession class and invoking the
getSession() method of your HttpRequest object:
import javax.servlet.http.* ;
HttpSession session = request . getSession ();
In JSP pages, session support is enabled by default, so it's as though those statements
have already been issued by the time the page begins executing. The session is available
implicitly through a session variable that's already set up for you.
The HttpSession section of the Java Servlet Specification defines the complete session
interface. Some representative session object methods are listed here:
isNew ()
Returns true or false to indicate whether the session began with the current request.
getAttribute (String attrName)
Session contents consist of attributes, which are objects bound to names. To access
a session attribute, specify its name. getAttribute() returns the Object bound to
the named session attribute, or null if there is no object with that name.
setAttribute (String attrName, Object obj)
Adds the object to the session and binds it to the given name.
removeAttribute (String attrName)
Removes the named attribute from the session.
invalidate ()
Invalidates the session and any data associated with it. The next request from the
client will begin a new session.
A sample JSP session application
The following example shows a JSP page, sess_track.jsp , that maintains a session request
counter and a log of the request times. To illustrate the session-related operations more
explicitly, this page consists primarily of embedded Java code that uses the HttpSes
sion session interface directly:
<%- -
sess_track . jsp : session request counting / timestamping demonstration
-- %>
<%@ page import = "java.util.*" %>
<%
// get session variables, initializing them if not present
int count ;
Search WWH ::




Custom Search