Java Reference
In-Depth Information
Objects can also be stored by a servlet as attributes at the session or application
scope. Had we wished to store the
SurveyData
instance as a session attribute,
we would have added the following line to the
processRequest()
method:
request.getSession().setAttribute("surveyData", surveyData);
The
getSession()
method of the
javax.servlet.http.HttpServletRequest
interface returns an instance of
javax.servlet.http.HttpSession
representing
the user's session. Session attributes are visible to all pages in a user's session, and
are preserved across requests.
Storing the instance of
SurveyData
at the application scope would have been
accomplished by the following line in the
processRequest()
method:
getServletContext().setAttribute("surveyData", surveyData);
The
getServletContext()
method is defined in
javax.servlet.GenericServlet
,
which is the parent class of
javax.servlet.http.HttpServlet
, that in turn is the
parent class of every servlet in a web application. This method returns an instance
of
javax.servlet.ServletContext
. Storing an object as an attribute of the servlet
context makes it visible across user sessions; therefore all users in the application
have access to the attribute.
Request, session, and application attributes can be retrieved by invoking
the
getAttribute()
method. This method exists in
HttpServletRequest
,
HttpSession
, and
ServletContext
. In all instances it takes a String parameter
indicating the name of the attribute to obtain, and returns an instance of
java.lang.
Object
, which then needs to be cast to the appropriate type. If there is no attribute of
the specified name, the method returns null.
The last thing we need to do in our example is to forward the request to
the output JSP, this is accomplished by obtaining an instance of
javax.
servlet.RequestDispatcher
, this instance is obtained by invoking the
getRequestDispatcher()
method of
javax.servlet.http.HttpServletRequest
,
this method has a single parameter, which is a String indicating the relative or
absolute URL of the page or servlet we wish to navigate to. In our example we are
using the relative URL of
output.jsp
, we know the URL is relative because all
absolute URLs begin with a forward slash (/). Once we have an instance of
javax.
servlet.RequestDispatcher
, we simply invoke its
forward()
method to navigate
to the desired page.
We need to make one minor modification to the input JSP page so that it invokes our
servlet when its form is submitted.