Java Reference
In-Depth Information
3.3.5
Using a JSP for the return trip
Here are the new elements to our refactored solution. First, let's take a look at
the performTask method in our servlet, which is now a true controller. It is
much simpler. A controller's job in Smalltalk is to handle the input and output
streams. Our controller is doing exactly that:
public void performTask(
HttpServletRequest request,
HttpServletResponse response) {
try {
PostListCommand postList = new PostListCommand();
Here, we are using the class loader to instantiate our bean. This bean will be
accessed by our JSP to print the results of the command's query that we'll exe-
cute next:
postList.initialize();
postList.execute();
request.setAttribute("PostListCommand", postList);
ServletContext servletContext = getServletContext();
RequestDispatcher dispatcher =
servletContext.getRequestDispatcher("/JSP/PostListResults.jsp");
dispatcher.forward(request, response);
} catch (Throwable exception) {
exception.printStackTrace();
}
}
These lines load the target JSP , which will use our executed command to print
the result set. They do three significant things. First, they put a reference to
our bean where our JSP can find it. Next, they get a dispatcher from the serv-
let context, which is used to call our JSP request page. Finally, they call the tar-
get result set JSP . (For a more robust application, we'd have pages for expected
error conditions as well.) We then catch our exceptions and go home.
Listing 3.6 contains the return trip, in the form of a JSP . Note that there is
no Java inline, except for a small amount to place dynamic content and to cre-
ate our table. That is intentional. For a good separation of concerns, we want
as little Java as possible.
Search WWH ::




Custom Search