Java Reference
In-Depth Information
into JSP files. The main servlet class ( BudgetProServlet.java ) is thus “gut-
ted” of its output, and the new version ( BudgetProController.java ) acts
as the controller. Requests come to it via HTTP requests, but for output, it
redirects the browser making that request over to the appropriate JSP.
This introduces a new bit of servlet syntax—redirecting a request to
another URL. The action is taken by means of a method call on the HTTP
response object:
response.sendRedirect("BPAcct");
Whereas in the previous, servlet version of BudgetPro, we would create an
object that was the next page of output:
nextPage = new AccountView(current);
In this version, we instead redirect the response to a JSP that produces the
output for that page.
So how does the JSP know for which account it should display informa-
tion? That is shared between the JSP and the controller servlet via the session
information. As with the previous, servlet-base BudgetPro, the session is used
to store the current account. It can be retrieved from the session information,
as seen in line 11 of BPAcct.jsp :
11: <% Account acct = (Account) session.getAttribute("current");
That variable ( acct ) is then used throughout the JSP to get the appropri-
ate data for display, as in:
21: Account: <%= acct.getName() %>
We could also have used a session JavaBean. Such a mechanism requires
more setup on both sides, the controller and the JSP, but has the advantage of
removing more literal Java code from the JSP. (“We leave this as an exercise for
the reader!”)
19.5
R EVIEW
We've looked at server-side Java processing with JavaServer Pages which can
be thought of as servlets turned inside out. From that simple concept we looked
Search WWH ::




Custom Search