Case Study Implementation - JSP

The Home page

Two items of special note are in Listing . One is the rather strange redirect at the top, which happens because in Tomcat welcome pages set up in web.xml cannot redirect to servlets, only JSP pages. Because this page needs to be visited via a controller servlet, the top of the JSP checks to see if this controller has been visited.This is because one of the roles of any controller is to initialize objects.The check at the top of the JSP simply queries one of these objects to see if it has been initialized. If it has not, the request is redirected to the controller.

The other notable feature of the home page shown in Listing , is the use of <jsp:include> rather than the <%@include> directive.The <jsp:include> action has been used to facilitate the straightforward modification of the HTML pages header.html and footer.html. If the include directive had been used, it would have meant that any changes to the pages would not have been represented in the output.The include directive results in the inclusion at compile time rather than runtime.This issue is discussed in Chapter ,“The Basic Syntax of JSP.”

Displaying the Course Information

When the user selects the Courses button from Figure they are redirected to a pagecalled courses.jsp.This page is shown in Listing .

Listing courses.jsp

The output is shown in Figure In Listing you can see that use is being made of both the core tags and the XML tags from the JSTL.

The property urls being used by this page is an array of URL objects that point to the XML files that contain the course information (as shown in Listing ).You’ll see how this is created when we look at the controller servlet.

courses.jsp in a browser.

courses.jsp in a browser.

This page is looping through these URLs and creating hyperlinks to the controllerservlet that also contains two parameters:

The parameter page sets the JSP that should receive the forwarded request (in this case, details.jsp), and the parameter index specifies the index of the course that is to be displayed by details.jsp.

The text for the hyperlink is generated using the XML-specific tags of the JSTL, andthey are processing the course XML files to extract the title of the course, and so on.This is displayed by the following code in Listing :

<a href=”gateway?page=/details.jsp&index=<c:out value=”${status.index}”/>”><x:out select=”$xml/course/title” /></a>

When a user clicks one of these hyperlinks, the next page to be displayed is details.jsp.This page has two functions: It presents the details of the specific course to the end user as HTML, and it provides a form for the user to request further information regarding the course.The top half of the output in the browser for details.jsp is shown in Figure

At the base of the course details is the booking form.This is shown in Figure The JSP code for details.jsp is shown in Listing.

details.jsp in the browser showing course information.

details.jsp in the browser showing course information.

details.jsp in the browser showing the booking form.

details.jsp in the browser showing the booking form.

Listing details.jsp

This page also uses the XML tags from the JSTL tag libraries, and this time it is to complete an XSLT transformation.The stylesheet is set up as an attribute by the controller servlet and is accessed via the xsl attribute (the controller servlet will be discussed in the next section).The stylesheet being used is shown in Listing

Listing courses.xsl

Notice that the stylesheet has none of the outer HTML tags such as <html> or <head> and so on.This is because the output from the transformation is displayed within the context of the page template shown in Figure .

The Controller Servlet

You have already seen that the controller servlet is responsible for n Setting up the xsl attribute used by details.jsp. n Setting up the urls attribute this contains an array of the XML file URLs thatcontain the course information. n Forwarding requests to the various pages based on the value of the page

The source for the controller servlet is shown in Listing


Every GET request will go through the controller servlets doGet() method. In this method, you can see that the first thing to be done is to initialize the url attribute if it is not already initialized.This is done by the private helper method setUpXMLURLs().The XML files follow a basic naming convention, which means that they are named coursex.xml, where x is an incremental number. In the application, there are three courses represented by the three files: course0.xml, course1.xml, and course2.xml.

The URLs are then placed into an array, which is then turned into an applicationscoped attribute: getServlet Context(). setAttribute (“urls”,xmlFiles);

The URL for the XSLT file is also set up as an application-scoped attribute from thishelper method:

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page); The processing of the data provided by the user needs to be looked at next. So far, you have seen that the user first navigates to courses.jsp and is presented with a list of courses.Then, when a course is selected via a hyperlink, the next page, details.jsp generates output showing the details about the course selected using an XSLT transformation.The page details.jsp also contains a form to enable the user to request further information about booking a particular course. It is this form, and the processing of this form data, that is to be discussed in the next section. Processing the Form

The form, although displayed as part of details.jsp, is actually contained within an include. Here is a snippet from details.jsp, shown in Listing

<jsp:include page=”orderCourse.jsp” flush=”true”/>

Listing shows the included page orderCourse.jsp.

Listing orderCourse.jsp

<%@ taglib uri=”” prefix=”c” %> <%@ taglib uri=”/WEB-INF/struts-html.tld” prefix=”html” %><hr><html:errors/>

Please complete the form below to order this course. A confirmation email will be sent to the address provided.


At the time of writing, dynamic values could not be used in the value attributes in the above Listing. Bythe time the book is out, containers will support the use of dynamic attribute values here. We were usingTomcat 4.1.2 beta.

Listing takes advantage of the Apache Struts framework, and therefore uses tagsfrom the Struts framework to build the HTML form. When the form is submitted, an object of a type that subclasses ActionForm is populated with the properties from the form.The subclass is ormonds.struts.OrderForm.This is shown in Listing


After a form is submitted the various set methods are invoked to populate the various OrderForm properties with the values from the form.After this has occurred, the validate() method is invoked, and this method will validate the form field values. So for example, the email address is checked to make sure it contains the @ and . in the right places because it will be used to send an email later.

The population of this OrderForm object happens because of the setup of the Struts application within the WEB-INFstruts-config.xml file.The key entries are shown here:

It is here, for example, that the /orderCourse.jsp form is linked to the OrderForm class.The form property names must match the Bean property names for the values in the OrderForm Bean to be populated from the form. If you look carefully at Listings and you can see that this is indeed the case. If an error is detected during validation, orderForm.jsp is displayed in the browser, but this time there is no surrounding content, and error messages are displayed at the top of the page.You can see below.

Displaying error messages.

Displaying error messages.

After the OrderForm.validate() method has been invoked, the appropriate Action object is invoked (as specified in struts-config.xml). In our example, the Action subclass is an instance of the ormonds.struts.OrderAction shown in Listing

Listing ormonds.struts.OrderAction

The OrderAction class initiates two main functions. One is to create, and then send anemail to the customer. The second is to update a MySQL database.Sending the EmailAfter the OrderForm.validate() method has returned with no errors, theOrderAction.perform() method is invoked.To enable the sending of an email there is the creation of a StringBuffer object that is to contain the text of the mail:

The text could have been extracted from a file or a property somewhere, but to keep it simple for now we have embedded it in the Java code.This message now needs to be sent. An additional Bean will do that for us.

If you have read the section of Chapter about Apache Struts, you will appreciate that the Action objects invoke the business logic, but do not normally contain it. The email is actually sent by an object of type This is shown in Listing, and it merits some explanation.

The classes used to send email are all from the javax.mail and javax.mail.internet packages, and they are commonly referred to as JavaMail, which is part of the J2EE platform. The classes and interfaces are within the Web application as part of the WEBINF libmail.jar archive.It also relies on the JavaBeans Activation Framework (JAF). The process of creating and sending an email when using JavaMail is as follows: Create a javax.mail. Session

The first step is to create a javax.mail.Session object, which is often used to hold the server name, username, password, and from address. Do not confuse this with the HttpSession! The Session object is obtained by invoking the static getInstance() method. A Properties object can be used to hold this information. Our values are set later in the code as you will see:

After the message has been created, it needs to be configured with a FROM address, a TO address, a subject, and the contents from the StringBuffer created by the OrderAction object.To set the TO and FROM addresses, we use another class, the

The addresses, the subject, and the message contents are then set on the MimeMessage using a series of set methods. After all the properties have been set, the headers of the message can be set based on the contents of the message.This is done using the

Sending the Message

To send the message, a javax.mail.Transport object is required which is obtained from the javax.mail.Session. This can then be used to send the message to the recipients:


If you want to test this, you will need to provide a genuine username, password, and server name. The send() method is used to send the message. After it has been sent, the transport should be closed using the close() method.

The OrmondsEmail sender class, although appropriate for low-volume Web sites such as Ormonds, would not be appropriate for all sites. Many sites send out email regularly to clients, and it is not usually good for performance to have this process being carried out by the same server that is serving up the Web content. However, a basic class like this would be appropriate for confirmation emails such as this. If Ormonds were using a high-end application server such as ATG Dynamo, which has a specialized personalization engine, this class would be redundant because this functionality is built in to the product.

Finally, we need to look at how the database is updated, and then how the Ormonds staff can access this information. Interacting with the Database

The database schema used by this application is shown in Listing

Listing tablesSetUp.sql.

The database used is MySQL and there are three tables in this schema; two are associated with the administration of users, which we will discuss later.The table that we need to pay attention to now is the orders table.There are fields for each of the values supplied by the online form shown in Figure

The OrderAction class shown in Listing shows that another class is being used to populate the database:

It is this OrmondsDataAccess class that we need to look at.This class has a method called update() that is invoked every time a form is submitted. It is shown in Listing


The code in this class is basic JDBC code that will update the database using a PreparedStatement. Most of this code should make sense to you because it is JDBC code, which was discussed in Chapter , “Databases and JSP.”

The database is then accessible via a page in the site that is only available to authorized Ormonds staff.The page is a protected resource called admin.jsp. It is shown in Listing

Listing admin.jsp

This listing uses the JDBC tags discussed in Chapter to access the table and interact with the database.What the page is doing is simply accessing the database table and displaying the results in an HTML table. It can be seen in Figure .

Securing the Administration Pages

Authorized users are the only ones with access to the administrative area; these users have been set up with the role of admin in the user_roles and user_table tables in the MySQL database.

For this to be configured, the following entry has been added into server.xml:

admin.jsp in a browser

admin.jsp in a browser


If you are planning to run this application on your machine, you will need to locate the <Realm ..> element after the <Engine name=”Standalone . . .”/> element, comment it out, and replace it with the <Realm> element shown above. See the readme.txt in the root folder of the Web application for more information.

The resources are then protected by the following entry in web.xml. In our application it is a single JSP:

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

JSP Topics