Java Reference
In-Depth Information
public Enumeration getAttributeNames()
public void removeAttribute(String name)
Collaborating with Servlets
Since servlets are often used in combination with JSPs, it is useful to consider the
methods that can be made use of to allow the two to collaborate easily. The two major
ways in which servlets and JSPs may wish to share information are the sharing of
data related to an individual user's session and the sharing of data related to the appli-
cation environment that is applicable to all users who visit the site. For JSPs, these
two categories of information are provided by the implicit objects session and
application respectively. We need to consider what objects will supply the same
information via servlets and how this information may be passed between servlets
and JSPs. It turns out that this is considerably easier than might at fi rst be thought.
If a Session object has already been created by a servlet (in the same session)
when a JSP is referenced, then the JSP implicit object session will contain any
attribute-value pairs that were placed in the original Session object. Thus, object
session may simply use its getAttribute method to retrieve any information stored by
the servlet.
Class HttpServlet implements interface ServletConfi g through its superclass,
GenericServlet . This interface has a method called getServletContext that returns a
ServletContext reference. In order to gain read/write access to environment-level
information, then, a servlet fi rst calls this method and stores the ServletContext ref-
erence that is returned. It then invokes methods getAttribute and setAttribute on the
ServletContext reference, in the same way that those methods are invoked on the
implicit object application in JSPs.
ServletContext context = getServletContext();
String userName =
Analogous to the situation with the sharing of session information, the object
application created when the JSP is fi rst referenced will automatically contain any
attribute-value pairs that have been set up previously by a servlet.
JSPs in Action
Now that the basic structure of a JSP has been explained and the allowable contents
identifi ed, it is time to look at an example JSP application. To illustrate how JSPs
may be used in collaboration with servlets, rather than having the dynamic content
Search WWH ::

Custom Search