Sharing Data Between the Component Types

When an application uses servlets, filters, and listeners as well as JSP pages, all components need access to shared data. For instance, you may want a JSP page to show the counter maintained by the session listener in Example 19-4, and let the servlet create beans and pass them to a JSP page for display.

This turns out to be very easy. The JSP request, session, and application scopes, described in Chapter 11, are just abstractions for the set of attributes the other component types can associate with various servlet objects they have access to: HttpServletRequest, HttpSession, and ServletContext, respectively. All these classes provide a set of methods that can be used to set, get, and remove attributes:

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

The session listener maintains the active session counter as a ServletContext attribute, as shown in Example 19-4, so a JSP page can access it as an application scope variable:

Number of active sessions: ${session_counter[0]}

Note how the JSTL EL expression uses the same variable name as the session listener uses for its ServletContext attribute. The EL locates the variable by looking for an attribute with the same name in the request, session, and context objects, in this order.

The same data is available to servlets and filters in the application since they all share the same ServletContext instance:

ServletContext ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.