[ Team LiB ] Previous Section Next Section

Passing Java Objects Between JSPs and Servlets

Although it is often convenient to just pass parameter strings between servlets and JSPs, you can't always fit everything you want into a string. If your servlet pulls some information from a database and you want to pass all that information to a JSP, you certainly don't want to convert all the information into strings. You are much better off just passing the Java objects containing the information.

In Hour 6, "Looking Under the Hood—Core Servlet Components," you saw that you can store Java objects in a session by calling getAttribute and setAttribute. You can use the session to pass data to an included page or to a forwarded servlet, but you don't really want that data hanging around in the session after you are done with it. You also don't want to add housekeeping code to the included page to clean up the variables stored in the session.

Luckily, there is a better solution. You can store Java objects in the request object using getAttribute, setAttribute, and removeAttribute, just as you can with a session object. The methods are identical to those in the session object, except that they can't throw IllegalStateException:


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

Because the request object exists only as long as the request is being processed, you don't have to worry about performing any cleanup. When you finish handling the request and have sent a response back to the browser, the request object disappears. The next time a request comes in, there is a new request object.

    [ Team LiB ] Previous Section Next Section