Home > Articles > Programming > Java

Constructing a Solution: Servlets, JSP, and JavaBeans

  • Print
  • + Share This
In this sample chapter, Paul Reed pulls together various technology puzzle pieces we and builds the first round of our architectural prototype.
This sample chapter is excerpted from Developing Applications with Java™ and UML, by Paul Reed.
This chapter is from the book

In This Chapter

In the last chapter we gave our user interface strategy a final review and then traced the communication from front to back as a means to solidify our architecture via a sequence diagram. This chapter focuses on pulling together the various technology puzzle pieces we have presented over the last three chapters and building the first round of our architectural prototype.

This portion of the Remulak solution will present both simple inquiry and update pathways through the Maintain Relationships use-case. The architecture will consist of Apache Tomcat as the servlet/JSP container and JavaBeans as the implementation for the entity classes. The JSPs will be identical between the two implementations, and the servlets will require only a small change to function in either environment.

GOALS

  • To review the services that Apache Tomcat has to offer and the role played in this phase of the solution.

  • To explore the user interface control class and how it brokers calls to the use-case control class.

  • To review the role of entity beans and how they implement the business rules of the application.

  • To look at the DAO classes in more depth and how they carry out the create, read, update, delete (CRUD) services of the entity beans.

Next Steps of the Elaboration Phase

Before constructing the first portion of the Remulak solution, let's revisit the Unified Process. FIGURE 11-1 shows the process model, with the focus on the Elaboration phase.

FIGURE 11-1 Unified Process model: Elaboration phase

In this chapter we will specifically focus on building code. This code will lead to the first attempt at an architectural prototype. The architectural prototype will be complete at the conclusion of the next chapter, in which we present an EJB solution. Now is also a good time to stress that there should be very few surprises, from an architecture and construction perspective, as we move through the remaining iterations in the Elaboration phase and then into Construction and Transition. Tasks will focus more on deployment and support as we move into Construction and Transition, but the real software architecture challenge happens early in Elaboration.

The following Unified Process workflows and activity sets are emphasized:

  • Analysis and Design: Design Components

  • Implementation: Implement Components

The emphasis now is to test our design strategies for how the code comes together.

Building the Architectural Prototype: Part 1

Part 1 of building the architectural prototype for our non-EJB solution covers the setup of the environment and the front components of the servlet and JSPs.

Baselining the Environment

Without the benefit of a commercial servlet/JSP container, we must turn to a solution that will be both flexible and able someday to migrate to a commercial product. The good news here is that the reference implementation for servlet/JSP containers was handed over by Sun Microsystems to the nonprofit Apache Software Foundation (jakarta. apache.org). Since that time, Tomcat has evolved at a rapid pace and is used by many organizations not only as a testing environment but in production settings as well. The features that commercial equivalents offer that are not offered by Tomcat tend to focus more on performance and less on functionality.

The first thing we must do is download the Tomcat binary from the Jakarta Project Web site (jakarta.apache.org). The instructions are very easy, so I won't bother describing the install process. If it takes more than five minutes, you're doing something wrong. After installing Tomcat and testing the install to see if it works, we are ready to begin our adventure into setting up the first part of the architectural prototype.

The next thing we'll need is both the latest version of the Java Development Kit (this project was built with JDK 1.3), as well as the latest version of the Java 2 Software Development Kit (this project was built with Java 2 SDK 1.2.1). To run the code from this chapter should require no classpath changes on your system because after you install Tomcat, you will copy the classes into the proper directories within Tomcat.

Personally, I wouldn't bother typing in the examples in this chapter and the next. What helps me the most is to get the source code and examine it, run it a little, then examine it some more. Just looking at these pages while you type the code is much less of a learning experience. As mentioned in the front of the book, you can get the code from two locations. The first is my Web site, at http://www.jacksonreed.com. The second is Addison-Wesley's Web site, at http://cseng.aw.com/. Download the code and unzip it into folders within the contained zip directory or put it into another, higher-level directory.

Setting Up the Environment

The implementation we are about to undertake would run just as well in IBM WebSphere or BEA WebLogic. The only difference is that we wouldn't be using the EJB features of these products. However, each is equally adept at running servlets, compiling JSPs, and managing JavaBeans. The EJB part of the commercial offerings is sometimes sold as an add-on component.

Where Tomcat is installed you will find a directory called webapps. On my machine it looks something like this:

C:\tomcat\Jakarta-tomcat-3.2.1\webapps 

Under this directory we want to add a new collection of directories. The first level will represent the application. I have called this one RemulakWebApp. Under this directory we create two subdirectories: images and WEB-INF. Under the WEB-INF directory we create two more subdirectories: classes and lib. The result should be something like this:

C:\tomcat\Jakarta-tomcat-3.2.1\webapps\RemulakWebApp\images 
C:\tomcat\Jakarta-tomcat-3.2.1\webapps\RemulakWebApp\WEB-INF 
C:\tomcat\Jakarta-tomcat-3.2.1\webapps\RemulakWebApp\ 
WEB-INF\classes 
C:\tomcat\Jakarta-tomcat-3.2.1\webapps\RemulakWebApp\ 
WEB-INF\lib 

The steps just described are not necessary if you want to just install the software from the book after the download. On a windows system, type in the following:

C:\javauml> xcopy /s /I RemulakWebApp %TOMCAT_HOME%\webapps\ 
   RemulakWebApp 

On a UNIX system, type in

[username /usr/local/javauml] cp –R RemulakWebApp $TOMCAT_ 
HOME/webapps 

Now start your Tomcat server and type in

http://localhost:8080/RemulakWebApp/ 

You should see something that looks like FIGURE 11-2 to confirm that the installation of Remulak was successful.

FIGURE 11-2 Initial default Web page for Remulak's Maintain Relationships use-case

Invoking Servlets

Servlets can be invoked in different ways. Actually, you can invoke a servlet from a Java application (non-browser-based client) running on a client machine if you so desire. We will use the standards set down in the Java specification and implemented not only in Tomcat but in all commercial servers, using a descriptor file. In the case of Web applications, this file is web.xml, and it resides in the root directory of your Web application. In the case of Remulak, the root directory would be RemulakWebApp.

<?xml version="1.0" encoding="ISO-8859-1"?> 
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web 
Application 2.2//EN" 
 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> 
<web-app>
   <display-name>Remulak Web Application</display-name>
   <servlet>
     <servlet-name>RemulakServlet</servlet-name>
     <servlet-class>com.jacksonreed.RemulakServlet</servlet-
      class> 
   </servlet>
     <servlet-mapping>
        <servlet-name>RemulakServlet</servlet-name>
        <url-pattern>/rltnInquiry</url-pattern> 
   </servlet-mapping>
   <servlet-mapping>
     <servlet-name>RemulakServlet</servlet-name>
     <url-pattern>/rltnUpdate</url-pattern> 
   </servlet-mapping>
   <welcome-file-list>
     <welcome-file>index.html</welcome-file> 
   </welcome-file-list>
   <aglib>
     <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
     <taglib-location>/WEB-INF/struts-bean.tld</taglib-
      location> 
   </taglib>
   <taglib>
     <taglib-uri>/WEB-INF/struts-form.tld</taglib-uri>
     <taglib-location>/WEB-INF/struts-form.tld</taglib-
      location> 
   </taglib>
   <taglib>
     <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
     <taglib-location>/WEB-INF/struts-logic.tld</taglib-
      location>
   </taglib> 
   <taglib>
     <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
     <taglib-location>/WEB-INF/struts-template.tld</taglib-
      location>
   </taglib> 
</web-app> 

Initially Remulak will use only one servlet, RemulakServlet. First find the <welcome-first> tag in the web.xml file. This tag indicates to the service running on the Web server the HTML page that it should send back if a specific page is not requested. In our case, we have indicated index.html.

The next piece of the XML file, which is by far the most important, consists of the <servlet-mapping> and <servlet-name> tags:

<servlet-mapping>
     <servlet-name>RemulakServlet</servlet-name>
     <url-pattern>/rltnInquiry</url-pattern> 
   </servlet-mapping>
   <servlet-mapping>
     <servlet-name>RemulakServlet</servlet-name>
     <url-pattern>/rltnUpdate</url-pattern>
</servlet-mapping> 

The <url-pattern> tag is used to identify, from the query string that comes from the browser, what servlet to invoke to process the request. In our case any string that contains /rltnInquiry/ or /rltnUpdate/ will be mapped to the servlet specified in the respective <servlet-name> tag. These two types of statements happen to map to the same servlet. The beauty of abstracting to the descriptor the name specified in the URL, as well as its mapping to the servlet, is that we can change the flow of the application for perhaps performance tuning or security without touching any code.

Any servlet that is specified in the <servlet-name> tag must also have a corresponding <servlet> tag. This tag specifies the class that implements the servlet. In our case it is the RemulakServlet class, which resides in the com.jacksonreed package.

<servlet>
     <servlet-name>RemulakServlet</servlet-name>
     <servlet-class>com.jacksonreed.RemulakServlet</servlet-
      class>
</servlet> 

If more servlets were desired, they would need to be reflected in the descriptor. A good design strategy might be to have a unique servlet for each use-case. When we explore our JSPs, I will mention the other tags in the web.xml file, especially the <taglib> tags.

The Servlet for Remulak: Broker Services

Remulak's servlet, RemulakServlet, was explored a bit in the sequence diagram presented in Chapter 10. We will now explore some of the code components of the servlet, starting initially with the main processing engine that is behind every servlet: the doGet() and doPost() operations:

package com.jacksonreed; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.io.*; 
import java.util.*; 

import java.util.Properties; 
import javax.naming.Context; 
import javax.naming.InitialContext; 
import javax.naming.NamingException; 
public class RemulakServlet extends HttpServlet { 
   private String url; 
   public void init() throws ServletException { 
      url = ""; 
   } 
   public void destroy() {
   } 
   public void doGet(HttpServletRequest request, 
      HttpServletResponse response) 
   throws IOException, ServletException { 
   doPost(request, response); 
} 
public void doPost(HttpServletRequest request, 
   HttpServletResponse response) 
   throws IOException, ServletException { 

   String action = request.getParameter("action"); 

   // Check which action to do and forward to it 
   if ("Customer Inquiry".equals(action)) { 
     doRltnCustomerInquiry(request, response); 
    } 
   else if ("New Customer".equals(action)) { 
     doRltnCustomerNew(request, response); 
    } 
   else if ("Edit Customer".equals(action)) { 
     doRltnCustomerEdit(request, response); 
    } 
   else if ("Delete Customer".equals(action)) { 
     doRltnCustomerDelete(request, response); 
    } 
   else if ("Add/Update Customer".equals(action)) { 
     doRltnCustomerAdd(request, response); 
    } 
   else if ("Edit Address".equals(action)) { 
     doRltnAddressEdit(request, response); 
    } 
   else if ("Delete Address".equals(action)) { 
     doRltnAddressDelete(request, response); 
    } 
   else if ("Add/Update Address".equals(action)) { 
     doRltnAddressAdd(request, response); 
    } 
   else if ("Add Address".equals(action)) { 
     doRltnAddressNew(request, response); } 
   else { 
     response.sendError(HttpServletResponse.SC_NOT_ 
     IMPLEMENTED); 
   } 
 } 
} 

The doPost() method is the main driver of RemulakServlet. Notice that the doGet() method simply calls doPost() where all the activity is. The request.getParameter("action") call retrieves the value of the action parameter that comes in as part of the query string, and on the basis of this value we branch to the appropriate operation to process this unique request. For instance, the query string that would come in after a customer number was entered into the form in FIGURE 11-2 would look like this:

". . . /RemulakWebApp/rltnInquiry?action=Customer+Inquiry& 
customerNumber=abc1234" 

This structure serves our purposes well and allows for easy branching to support different functions of the application. However, it does make for additional maintenance, should you want to add more actions in the future. Although I have chosen this route to show you the semantics of the whole application interaction and to avoid more complicated abstractions, I encourage you to look at some of the interesting alternatives offered by other authors and practitioners.

The first one I direct you to is Hans Bergsten's Java Server Pages (published by O'Reilly, 2001). This book introduces the notion of "action" classes that are driven by an XML descriptor. These action classes deal with the unique processing necessary for each request. So to add more actions, you write the action class and update the XML descriptor. There is no need to recompile the servlet.

The second source is from the same folks who gave us Tomcat—that is, the Apache group's Struts framework (jakarta.apache.org). Struts covers many aspects of the management of user interface editing, including brokering calls within the servlet. Struts also uses action objects just as in Bergsten's approach. We will use Struts in Chapter 12 to provide a looping capability to our JSPs.

The Servlet for Remulak: Responding to an Action Request

The next aspect of the servlet to explore is how it responds to the action requests. We have already shown how the servlet determines which action to carry out. The following code deals with carrying out the request:

private void doRltnCustomerInquiry(HttpServletRequest 
request, HttpServletResponse response) 
           throws IOException, ServletException { 
String customerNumber = request.getParameter("customerNumber");
 
           if (customerNumber == null) { 
               throw new ServletException("Missing 
               customerNumber info"); 
           } 
           UCMaintainRltnshp UCController = new 
           UCMaintainRltnshp(); 

           // Call to method in controller bean 
           CustomerValue custVal = 
                UCController.rltnCustomerInquiry(customerNumber); 

           // Set the custVal object into the servlet context so
           // that JSPs can see it
           request.setAttribute("custVal", custVal); 
           // Remove the UCMaintainRltnshp controller 
           UCController = null; 

           // Forward to the JSP page used to display the page 
           forward("rltnInquiry.jsp", request, response); 
     } 

The doRltnCustomerInquiry() method is a heavily requested pathway through the Maintain Relationships use-case. Once invoked from the doPost() method, it first retrieves the customerNumber attribute that came in with the query string via the getParameter() message to the servlet's Request object. The next step is to instantiate the use-case control class: UCMaintainRltnshp. Now with an instance of the controller available, the servlet can send messages to the rltnCustomerInquiry() operation in the controller. Remember from the sequence diagram that the result of this message brings back the proxy object that represents the state of a Customer object: CustomerValue. Later in this chapter we will explore the details of the control, bean, and DAO classes involved. The CustomerValue object is inserted into the servlet's Request object so that it can be accessed by our JSPs. Then a message is sent to a forward() operation that is common across all the requests that the servlet processes:

private void forward(String url, HttpServletRequest request,
     HttpServletResponse response)
     throws IOException, ServletException {

     RequestDispatcher rd = request.getRequestDispatcher
     (url);
     rd.forward(request, response);
}

The forward() request retrieves the submitted JSP and then processes the results, which look like FIGURE 11-3.

FIGURE 11-3 Results of Remulak customer query

Let's now look at the operation that handles adding and updating of a Customer object:

private void doRltnCustomerAdd(HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {

   UCMaintainRltnshp UCController = new UCMaintainRltnshp();
   CustomerValue custVal = setCustomerValueFromForm(request);

   if (request.getParameter("customerId").length() == 0) {
     UCController.rltnAddCustomer(custVal); //Add
   }
   else {
     UCController.rltnUpdateCustomer(custVal); //Update
   }

   custVal = UCController.rltnCustomerInquiry
     (custVal.getCustomerNumber());

   UCController = null;

   request.setAttribute("custVal", custVal);

   forward("rltnInquiry.jsp", request, response);
}

This operation has many similarities to the doRltnCustomer Inquiry() operation. It also sends messages to the control class, UCMaintainRltnshp, to get its work done. But before doing that, it must transfer the values from the Request object into a proxy CustomerValue object to be sent through layers, resulting in some type of database update (insert or update). The setCustomerValuesFromForm() operation does this for us:

private CustomerValue setCustomerValueFromForm
     (HttpServletRequest request)
     throws IOException, ServletException {

  CustomerValue custVal = new CustomerValue();
  if (request.getParameter("customerId").length() > 0) {
    Integer myCustId = new Integer
         (request.getParameter("customerId"));
    custVal.setCustomerId(myCustId);
  }
  custVal.setCustomerNumber
     (request.getParameter("customerNumber"));
  custVal.setPrefix(request.getParameter("prefix"));
  custVal.setFirstName(request.getParameter("firstName"));
  custVal.setMiddleInitial
     (request.getParameter("middleInitial"));
  custVal.setLastName(request.getParameter("lastName"));
  custVal.setSuffix(request.getParameter("suffix"));
  custVal.setPhone1(request.getParameter("phone1"));
  custVal.setPhone2(request.getParameter("phone2"));
  custVal.setEMail(request.getParameter("eMail"));

  return custVal; 
} 

Notice that this mapping code begins by creating a new Customer Value object. Then it has to determine if it is doing this as a result of a new customer being added or if this customer already exists. The distinction is based on a hidden field in the HTML placed there during the processing of an inquiry request. The hidden field is customerId. A customer ID will not have been assigned yet if the customer is being added, so this field is the determinant. The remaining code just cycles through the form fields populating CustomerValue.

Let's go back to the doRltnCustomerAdd() operation. After the fields are populated, a message is sent to the controller either asking for a customer to be added (rltnAddCustomer()) or asking for a customer to be updated (rltnUpdateCustomer()). The customer is then queried again through the rltnCustomerInquiry() operation of the controller, and the customer is displayed via the rltnInquiry() JSP. FIGURE 11-4 is a screen shot of the form used both to update an existing customer and to add a new customer; it is the output from the rltnCustomer() JSP.

FIGURE 11-4 Results of Remulak customer add/update request

The remaining operations within RemulakServlet follow. For the sake of brevity, I have stripped out the comments that exist in the code because they look very similar to the comments in doRltnCustomer Inquiry():

   private void doRltnCustomerNew(HttpServletRequest request,
     HttpServletResponse response)
     throws IOException, ServletException {

     CustomerValue custVal = new CustomerValue();
     request.setAttribute("custVal", custVal);

     forward("rltnCustomer.jsp", request, response);
   }
   private void doRltnCustomerEdit(HttpServletRequest request,
     HttpServletResponse response)
     throws IOException, ServletException {

     String customerNumber = request.getParameter
     ("customerNumber");

     UCMaintainRltnshp UCController = new UCMaintainRltnshp();
 
     CustomerValue custVal =
         CController.rltnCustomerInquiry(customerNumber);
     request.setAttribute("custVal", custVal);

     UCController = null;

     forward("rltnCustomer.jsp", request, response);
   }
   private void doRltnCustomerDelete(HttpServletRequest
   request,
     HttpServletResponse response)
     throws IOException, ServletException {

     String custId = request.getParameter("customerId");

     Integer customerId = new Integer(custId);
     UCMaintainRltnshp UCController = new
     UCMaintainRltnshp();

     UCController.rltnDeleteCustomer(customerId);

     UCController = null;

     response.sendRedirect
         ("http://localhost:8080/RemulakWebApp/rltnEntry.
         html");
     return;
   } 

This is a fairly concise view of RemulakServlet. However, it is only for strictly the Customer portion of the Maintain Relationships use-case. Recall from the doPost() operation reviewed earlier that there were operations such as doRltnAddressAdd() and doRltnAddressDelete(). We will review this aspect of the Maintain Relationships use-case and inquire on all its related objects when we visit the EJB solution in Chapter 12.

JavaServer Pages for Remulak

Before moving toward the back end in our review of the use-case control classes and DAO classes, it's a good idea to talk about how the user interface, or the view, is handled. Remember that JSPs serve the role of our view in the MVC framework. JSPs operate on objects placed into the Request scope by the servlet. By separating the very volatile view from the more stable model, we insulate the application from future maintenance and technology changes. This combination of servlets and JSPs has a name: Model 2. (Model 1 applications are just JSPs playing both the role of broker and output page formatting.)

At first glance, JavaServer Pages seem like a hodge-podge of elements: scripting, HTML, Java code, and tag library references. After working with them, however, you will appreciate them not just for their speed but also for their flexibility. Again, my coverage of JSP can't do the entire topic justice. So I refer you to the previously mentioned JSP book by Hans Bergsten for exhaustive coverage.

Let's start by jumping right into a JSP for Remulak, the rltn Inquiry JSP:

<%@ page language="java" contentType="text/html" %>
<jsp:useBean id="custVal" scope="request"
     class="com.jacksonreed.CustomerValue" />
<HTML>
<HEAD>
<TITLE>Remulak Relationship Inquiry</TITLE>
</HEAD>
<BODY >
<form action="rltnUpdate" method="post">
<P><FONT size=6>Remulak Relationship Inquiry</FONT></P>
<table border="1" width="20%" >
  <tr>
    <th align="center">
      Customer Number
    </th>
  </tr>
  <tr>
    <td align="left" bgColor="aqua">
       <%= custVal.getCustomerNumber() %>
    </td>
  </tr>
</table>
<p><p>
<table border="1" width="60%" >
<tr>
  <th align="center" width="10%">
    Prefix
  </th>
  <th align="center" width="25%">
    First Name
   </th>
   <th align="center" width="2%">
     MI
  </th>
  <th align="center" width="25%">
     Last Name
  </th>
  <th align="center" width="10%">
     Suffix
  </th>
  </tr>
  <tr>
    <td align="left" width="10%" bgColor="aqua">
      <jsp:getProperty name="custVal" property="prefix"/>
    </td>
    <td align="left" width="25%" bgColor="aqua">
      <%= custVal.getFirstName() %>
    </td>
    <td align="left" width="2%" bgColor="aqua">
      <%= custVal.getMiddleInitial() %>
    </td>
    <td align="left" width="25%" bgColor="aqua">
      <%= custVal.getLastName() %>
    </td>
    <td align="left" width="10%" bgColor="aqua">
       <%= custVal.getSuffix() %>
    </td>
  </tr>
</table>
<p><p>
<table border="1" width="60%" >
  <tr>
  <th align="center" width="25%">
    Phone1
   </th>
   <th align="center" width="25%">
     Phone2
  </th>
  <th align="center" width="25%">
    E-Mail
  </th>
  </tr>
  <tr>
    <td align="left" width="25%" bgColor="aqua">
       <%= custVal.getPhone1() %>
    </td>
    <td align="left" width="25%" bgColor="aqua">
       <%= custVal.getPhone2() %>
    </td>
    <td align="left" width="25%" bgColor="aqua">
       <%= custVal.getEMail() %>
    </td>
  </tr>
</table>
<!--Buttons for Customer -->
<table border="0" width="30%" >
  <tr>
    <th align="left" width="33%">
      <INPUT type=submit value="Edit Customer" name=action >
    </th>
    <th align="left" width="33%">
       <INPUT type=submit value="Delete Customer" name=action >
    </th>
    <th align="left" width="33%">
       <INPUT type=submit value="Add Address" name=action>
    </th>
  </tr>
</table>
<INPUT type="hidden" name="customerNumber"
      value='<%= custVal.getCustomerNumber() %>' >
<INPUT type="hidden" name="customerId"
      value='<%= custVal.getCustomerId() %>' >
</form>
</BODY>
</HTML>

A JavaServer Page consists of three types of elements: directives, actions, and scripts. Directives are global definitions that remain constant across multiple invocations of the page. Items such as the scripting language being used and any tag libraries are common directives found in most JSPs. Directives are always enclosed by <%@ . . . %>. In the rltnInquiry() page above, the page directive is a good example of a directive.

Actions, or action elements, are uniquely processed for each page request. A good example would be the CustomerValue object mentioned previously that is placed into the Request scope by the servlet. The ability to reference the attributes within the page during execution is an action. There are several standard actions, such as <jsp:useBean>, that are always found in JSPs. In the rltnInquiry JSP, the useBean action tag is defining a reference item, custVal, that is implemented by the com.jacksonreed.CustomerValue class. If you look down about forty lines in the JSP, you will run across a <jsp:getProperty> tag for the prefix field for the customer. This tag is referencing the element defined by the useBean tag.

Scripts, or scripting elements, let you add actual Java code, among other things, to the page. Perhaps you need a branching mechanism or a looping arrangement; these can be created with scripts. Scripts are easy to identify because they are enclosed by <% . . . %>, <%= . . . %>, or <%! . . . %>, depending on what you're trying to do. If you revisit the rltnInquiry page above, right after the prefix action reference you will see a script displaying the first name field. The <%= custVal. getFirstName()%> scripting element contains an actual line of Java code that is executing the getter for the first name.

As powerful as scripting elements are, they should be avoided. They make maintenance more difficult, and they clutter up the JSP. It is much better today to use tag libraries, such as Struts, which encapsulate most of the logic for you. Your motto should be to have as little scripting as possible in your JSPs.

The rltnInquiry page is simply utilizing the information in the CustomerValue object, which was inserted by the servlet, to build a table structure with returned values. Notice the hidden fields at the bottom of the page. These are used to facilitate some of the action processing in the servlet. When we explore the EJB solution for Maintain Relationships, more will be added to this page to facilitate looping through all the Role/Address combinations for the Customer object. That's where we will use some of the features of Struts.

The rltnCustomer page is used to both add and update a Customer object. Here's the JSP behind the screen display in FIGURE 11-4:

<%@ page language="java" contentType="text/html" %>
<jsp:useBean id="custVal" scope="request"
      class="com.jacksonreed.CustomerValue" />
<HTML>
<HEAD>
<TITLE>Remulak Customer Add/Update</TITLE>
</HEAD>
<BODY >
<P><FONT size=6>Remulak Customer Add/Update</FONT></P>

<%--Output form with submitted values --%>
<form action="rltnUpdate" method="get">
  <table>
    <tr>
      <td>Customer Number:</td>
      <td>
        <input type="text" name="customerNumber"
             value="<jsp:getProperty name="custVal"
             property="customerNumber"/>">
      </td>
    </tr>
    <tr>
      <td>Prefix:</td>
      <td>
        <input type="text" name="prefix"
          value="<jsp:getProperty name="custVal"
          property="prefix"/>">
      </td>
    </tr>
    <tr>
   <td>First Name:</td>
   <td>
       <input type="text" name="firstName"
         value="<jsp:getProperty name="custVal"
         property="firstName"/>">
   </td>
  </tr>
  <tr>
    <td>Middle Init:</td>
    <td>
       <input type="text" name="middleInitial"
         value="<jsp:getProperty name="custVal"
         property="middleInitial"/>">
    </td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td>
      <input type="text" name="lastName"
        value="<jsp:getProperty name="custVal"
        property="lastName"/>">
    </td>
  </tr>
  <tr>
    <td>Suffix:</td>
    <td>
      <input type="text" name="suffix"
        value="<jsp:getProperty name="custVal"
        property="suffix"/>">
    </td>
  </tr>
<tr>
    <td>Phone #1:</td>
    <td>
      <input type="text" name="phone1"
         value="<jsp:getProperty name="custVal"
         property="phone1"/>">
    </td>
  </tr>
  <tr>
    <td>Phone #2:</td>
    <td>
      <input type="text" name="phone2"
        value="<jsp:getProperty name="custVal"
        property="phone2"/>">
    </td>
  </tr>
  <tr>
    <td>EMail:</td>
    <td>
      <input type="text" name="eMail" size=30
         value="<jsp:getProperty name="custVal"
         property="EMail"/>">
    </td>
  </tr>
</table>
<INPUT type="hidden" name="customerId"
       value="<jsp:getProperty name="custVal"
       property="customerId"/>">
<INPUT type=submit value="Add/Update Customer" name=action>
</form>
</BODY>
</HTML>

Both JSP pages—rltnInquiry() and rltnCustomer()—have all three types of elements: directives, actions, and scripts.

  • + Share This
  • 🔖 Save To Your Account