[ Team LiB ] Previous Section Next Section

Storing Data in a session Object

When dealing with HTTP, there is no permanent connection between a browser and a Web server. When the browser needs a page from the Web server, it opens a connection, retrieves the page, and then closes the connection. After that, the Web server has no idea what is happening on the browser. The browser could crash, or the entire client computer could be turned off, and the Web server would be oblivious.

HTTP Persistent Connections

graphics/bytheway_icon.gif

Because opening and closing connection is time-consuming, HTTP 1.1 provides a mechanism to keep a connection open during the exchange of requests and responses between a client and server. A persistent connection can remain open until either the client or server decides to close the connection. However, HTTP remains stateless as far as the application is concerned.


Furthermore, when another connection is made, the Web server does not associate the new connection with any other that has been made in the past. In other words, HTTP is not session-oriented.

Sessions allow an application to remember something about a client that persists between connections. In the first part of this hour, we saved information that we did not want to forget by passing it back and forth between the client and application. In this way, we created a primitive session.

Servlets and JSPs do have a notion of a session. Instead of playing toss with variables, servlets and JSPs can store information on the server using a single key that the client remembers. Servlets and JSPs use an HttpSession object to accomplish this.

Using the session Object in a JSP

JavaServer Pages have several built-in objects. You have already seen two of them: request and out. The next important one is called session, and it's an instance of HttpSession. The three methods that you use the most in the session object are getAttribute, setAttribute, and removeAttribute. The declarations for these methods are


public void setAttribute(String name, Object value)
    throws IllegalStateException
public Object getAttribute(String name)
    throws IllegalStateException
public void removeAttribute(String name)
    throws IllegalStateException

These methods act much like the get and put methods in the Hashtable class. That is, setAttribute associates a name with a value, and getAttribute returns the value associated with a name or returns null if there is no value associated. For example, to store some data in a session, you would type the following:


session.setAttribute("someKey", "here is my data");

To retrieve the data back out of the session, you would type this:


String myData = (String) session.getAttribute("someKey");

An IllegalStateException is thrown when you try to get or set an attribute on an invalid session. A session becomes invalid either when you call its invalidate method or after the session has timed out. The servlet engine keeps track of how long it has been since a session has been accessed; after a certain period of inactivity, the session is marked as invalid. You can configure the amount of time it takes to time out a session, either on a per-session basis or for all sessions.

Specifying the Session Timeout Duration

graphics/bytheway_icon.gif

The Servlet API specifies a way for you to control the timeout period on a per-session basis. Most servlet engines also provide a way for you to specify a default timeout length, but the Servlet API does not require them to.


Listing 12.4 shows the Login.jsp page modified to support the session object. Notice that it no longer needs to use hidden form variables.

Listing 12.4 Source Code for Login2.jsp
<%@ page language="java" import="java.util.*" %>


<html>
<body bgcolor="#ffffff">

<%
// Get the login information.
    String userName = request.getParameter("username");
    String password = request.getParameter("password");

// Store the username in the session.
session.setAttribute("username", userName);
%>
Welcome, <%=userName%>!
<form action="ColorServlet2" method="POST">

<p>
Please enter your favorite color:
<select name="color">
    <option value="blue" SELECTED>Blue</option>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="yellow">Yellow</option>
    <option value="mauve">Mauve</option>
</select>
<p>
<input type="submit" value="Choose color!">
</form>
</body>
</html>

Having Trouble with the Example?

graphics/bytheway_icon.gif

If you are having trouble storing or retrieving your session information, see the "Q&A" section at the end of this hour.


Using the session Object in a Servlet

You have probably guessed this already, but the session object you use in a servlet is identical to the one you use in a JSP. The only difference is that it isn't already conveniently sitting around in a variable named session. Instead, you must get the session object from the request object.

JSPs Automatically Obtain a Session

graphics/bytheway_icon.gif

JavaServer Pages also get the session object from the request object. The only reason you don't notice is that the JSP compiler automatically generates code to fetch the session object and put it in a variable named session.


To get the session object from the request object, just call the getSession method:


HttpSession session = request.getSession();

Inside a servlet, you use the same getAttribute and setAttribute methods to update session variables as you do in a JSP. After all, the session object is an instance of HttpSession in both a servlet and a JSP.

Obtain a Session Before Starting Your Response

graphics/watchout_icon.gif

Because the servlet engine needs to send a session cookie back to the browser, make sure that you get the session object before you start sending a response back to the browser. Cookies must be sent back in the header portion of the response. In a JSP, the session object is usually available immediately. You really need to worry about this only inside a servlet.


Listing 12.5 shows the necessary modifications to ColorServlet to make it use HttpSession rather than form variables.

Listing 12.5 Source Code for ColorServlet2.java
package examples;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class ColorServlet2 extends HttpServlet
{
    public void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws IOException
    {
// Tell the Web server that the response is HTML.
        response.setContentType("text/html");

// Get the PrintWriter for writing out the response.
        PrintWriter out = response.getWriter();

// Fetch the color parameter.
        String color = request.getParameter("color");

// Get the username from the session.
        HttpSession session = request.getSession();

        String userName = (String) session.getAttribute("username");

// Write the HTML back to the browser.
        out.println("<html>");
        out.println("<body bgcolor=\"#ffffff\">");
        out.println("Well, I see that "+userName+
            "'s favorite color is "+color+".");
        out.println("</body>");
        out.println("</html>");
    }
}

HttpSessions Work Only in HttpServlets

graphics/bytheway_icon.gif

Because the HttpSession object relies specifically on features of HTTP, you can use it only in servlets that are subclasses of HttpServlet.


    [ Team LiB ] Previous Section Next Section