Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

19.4 Using JSP with BudgetPro

We could have taken the BudgetPro example from the previous chapter and simply translated it all into JSP files. The reason we didn't is that it's not how you are likely to find JSP used "in the wild." Since JSP files become servlets, it is not uncommon to find JSP and servlets mixed together&8212;not arbitrarily, but in a sensible way. Remember the Model/View/Controller (MVC) pattern from your readings on object-oriented programming and design patterns? [2] Well, JSP makes for a reasonable View, and a plain servlet can act as the Controller. The Model is typically the database behind all this. That's what we've done with the BudgetPro example.

We've taken the two main chunks of output code&8212;that for the main account display and the form used for creating subaccounts&8212;and turned those into JSP files. The main servlet class (BudgetProServlet.java) is thus "gutted" 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&8212;redirecting a request to another URL. The action is taken by means of a method call on the HTTP response object:


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 information? 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 appropriate 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!")

  • + Share This
  • 🔖 Save To Your Account