|
Write a Different Base Class
Provide your own base class to extend JavaServer Pages in a simple application that performs a calculation
by Kevin Jones
Posted January 14, 2004
Recently I needed to write a very simple Web application that consisted of not more than a couple of pages. Going down the full Model-View-Controller (MVC) route for this task seemed to be overkill; however, I didn't want to fall into the trap of adding Java code to the JavaServer Pages (JSP) I was using. To overcome these problems I decided to write a JSP and then have it extend a base class that I wrote rather than whatever base class the JSP compiler provided. This tact gave me a reasonably simple solution and also kept my "separation of concerns"—code in the Java base class—layout in the JSP. Let's look at how to write and use this base class.
To examine the process for writing and using the base class we'll use a mortgage calculator as an example. The page is called MortgageCalc.jsp (see Figure 1 for a look at the rendered page). When you press the Calculate Payment button, it sends a request back to the MortgageCalc.jsp. This page then needs to calculate the payments.
One way to carry out the calculation would be to include the calculation in the JSP page (see Listing 1). The MortgageCalc class carries out the calculation. Notice that in the code block we test the various parameters that can be passed as part of the request, calculate the mortgage, and then store the MortgageCalc object in page scope by using the pageContext object. Once the MortgageCalc object is in scope the JSP can then access its properties by executing an expression:
<input name="txtMonthlyIns" type=
"text" id="txtMonthlyIns"
value=
"${payments.monthlyInsurance}"
/></td>
This example uses the ExpressionLanguage introduced in JSP 2.0.
Though this all works it doesn't smell right. Putting code into a JSP is always a bad idea. JSP is about user interfaces and any code, but business logic in particular should be avoided.
One way around this problem is to provide a servlet that acts as a controller with a bean acting as the model and having the calculation in the bean. This solution would be overkill for a small application such as this. Another solution would be to create a Java object to which you pass the HttpServletRequest; the object would read the parameters from the request and carry out the calculation. This solution still leaves the issue of having to have some Java code on the page, that is, the code to create and initialize the object and store the object in the pageContext.
Back to top
|