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

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
           // 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.4 specification.