toc

Team LiB
Next Section

Java InstantCode: Developing JSP and XML Integrated Solutions
Java InstantCode: Developing JSP and XML Integrated Solutions
SkillSoft © 2004

Use this code-intensive reference to learn about developing JSP and XML integrated solutions using XML-based JSP documents, the Java API for XML Processing (JAXP), and JDOM.

Has CD Content
Table of Contents
 | Introduction
 | Copyright
 | Point 1 | - | Creating Web Applications Using XML-Based JSP Documents
 | Point 2 | - | Creating a JSP Application to Process and Transform XML Documents Using JAXP
 | Point 3 | - | Creating a JSPXML Integrated System Using JDOM
 | Point 4 | - | Generating Dynamic XML Content in JSP Applications
 | Point 5 | - | Developing JSP Custom Tags for Integrating and Displaying XML Data
 | Point 6 | - | Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications
 | Point 7 | - | Creating an Internationalized Application Using JSP and XML
 | Index
 | List of Figures
 | List of Examples
 | CD Content CD Content

Team LiB
Next Section


Introduction

About InstantCode Books

The InstantCode series is designed to provide you - the developer - with code you can use for common tasks in the workplace. The goal of the InstantCode series is not to provide comprehensive information on specific technologies - this is typically well-covered in other books. Instead, the purpose of this series is to provide actual code listings that you can immediately put to use in building applications for your particular requirements.

How These Books are Structured

The underlying philosophy of the InstantCode series is to present code listings that you can download and apply to your own business needs. To support this, these books are divided into chapters, each covering an independent task.

Each chapter includes a brief description of the task, followed by an overview of the element of the book's subject technology that we will use to perform that task. Each section ends with a code listing: each of the individual code segments in the chapter is independently downloadable, as is the complete chapter code. You will be able to download source code files, as well as application files.

Who Should Read These Books

These books are written for software development professionals who have basic knowledge of the associated technology and want to develop customized technology solutions.

Team LiB


About the Book

This book describes J2EE solutions developed using JavaServer Pages (JSP) and Extensible Markup Language (XML). The book explains developing JSP and XML integrated solutions using XML-based JSP documents, the Java API for XML Processing (JAXP), and JDOM. The book also explains how to develop custom tags and use pre existing tag libraries for XML processing in J2EE applications. In addition, the book describes how to generate dynamic XML contents from J2EE application and integrate XML to develop internationalized Web applications.

About the Author

Simanta Sarma holds a Bachelor's degree in Engineering and an advanced diploma in Web computing. He is proficient in Web, distributed, and enterprise technologies developed in J2EE. He has designed and authored numerous books, courseware and articles on J2EE technologies.

Credits

I would like to thank Radhika Chauhan, S Sripriya, and Parag Phukan for helping me complete the book on time. I also thank the editors and the quality assurance team for their timely help.


Copyright

Java InstantCode: Developing JSP amd XML Integrated Solutions

Copyright © 2004 by SkillSoft Corporation

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of SkillSoft.

Trademarked names may appear in the InstantCode series. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

Published by SkillSoft Corporation
20 Industrial Park Drive
Nashua, NH 03062
(603) 324-3000

information@skillsoft.com

The information in this book is distributed on an "as is" basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author nor SkillSoft shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.


Point 1: Creating Web Applications Using XML-Based JSP Documents

JavaServer Pages (JSP) is a Java 2 Enterprise Edition (J2EE) technology to develop dynamic Web applications. In JSP applications, an alternative to relational databases to store application data is eXtensible Markup Language (XML) documents. XML documents provide a hierarchical format to store application data using meaningful tags without the overhead of a separate database server.

To integrate XML in JSP applications, you need to access and store data to and from the XML documents. There are several Application Programming Interfaces (APIs), such as Document Object Model (DOM), Simple API for XML (SAX), and JDOM that allow manipulation of XML documents from JSP pages. In addition, you can use standard tag libraries, such as Java Standard Tag Library (JSTL) or create your own custom tag library to work with XML documents from JSP pages. You can also develop XML-based JSP pages, known as JSP documents to develop Web applications.

XML-based JSP documents are JSP pages written in XML syntax. A JSP document must comply with XML specifications. All JSP documents need to have a root tag,<jsp:root>, which includes other subtags. You save JSP documents as .jspx files and deploy them on J2EE application servers.

Developing XML-based JSP documents allows you to create structured Web pages using XML-based tools. JSP documents also enable document validation against an external Document Type Definition (DTD) or schema to ensure consistent document structures.

This chapter describes how to create a dynamic Web application using XML-based JSP documents. The application is an online retail application that allows you to develop JSP documents using XML syntax for JSP declarations, JSP page directives, JSP expressions, and JSP scriptlets.

Requirements for Online Retail Application

The online retail application allows registered end-users to log on to the Web site, view a list of all the items in the store, determine the available quantity and price of each item, and place orders for various items. To record the orders placed by an end-user, the application maintains a list of orders sorted by date and time. This allows end-users to view order information.

You can develop the online retail application by integrating the following three modules:

  • Logon module: Authenticates end-users. The files in the Logon module are:

    • Logon.jspx: Displays a text field and a password field to obtain information about end-users.

    • DoLogon.jspx: Accesses a JavaBean component to authorize an end user to access the retailer's Web site.

    • LogonHandler.java: Accesses a back-end database to validate end user information.

    • User.java: Represents the end-user's logon information and role. An end-user of the Web site can be assigned either the user or the administrator role.

  • User module: Allows end-users to view item information, purchase items, and view sales reports of all the items purchased. The user module contains the following files:

    • UserPage.jspx: Displays hyperlinks to the other pages of the user module.

    • ViewAllItems.jspx: Displays all the available items in the store.

    • PurchaseItems.jspx: Displays the user interface that the end user uses to purchase items.

    • DoPurchase.jspx: Records information about the purchases made by an end-user.

    • ViewTotalPurchase.jspx: Displays all purchases made by an end user.

  • Administrator module: Allows the administrator to log on, update item information, record new item information, and view sales records and a list of all the available items in the store. The user module contains the following files:

    • AdminPage.jspx: Displays hyperlinks to the other pages of the administrator module.

    • ManageItems.jspx: Allows the administrator to add, update, and delete information about items.

    • GetAllItems.jspx: Displays the user interface to add, update, and delete information about items.

    • AddItem.jspx: Records information about new items added to the store.

    • UpdateItem.jspx: Updates information about available items.

    • ViewSales.jspx: Displays sale information about all the purchases.

    • ViewAllItems.jspx: Displays all the available items of the store.

Figure 1-1 shows the architecture of the online retail application:

Click To expand: This figure shows the various files used in the online retail application and the sequence in which they are used.
Figure 1-1: Architecture of the Online Retail Application


Creating Database Tables

The online retail application uses the Java Server Pages Extensible Markup Language (JSPXML) database, which contains the User, Item, and PItem tables. Listing 1-1 shows the database.sql file, which contains the Transact-SQL (T-SQL) script to create the tables of the JSPXML database and insert sample data:

Listing 1-1: The database.sql File
Start example
Use JSPXML
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Item]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Item]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PItem]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[PItem]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[User]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[User]
GO
CREATE TABLE [dbo].[Item]
(
   [ItemCD] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   [ItemName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   [Price] [int] NULL,
   [Qty] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PItem]
(
   [ItemCD] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   [UserID] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   [Date] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   [Qty] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[User]
(
   [UserID] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   [Password] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   [Role] [int] NULL
) ON [PRIMARY]
GO
Insert Into [User] Values('admin','admin',1)
Insert Into [User] Values('Peter','peter',2)
Insert Into [User] Values('Sara','sara',2)
GO
End example

Download this listing.

The above code creates the User, Item, and PItem tables of the JSPXML database. The code also inserts sample data in the User table.


Creating the Logon Module

The logon module of the online retail application authenticates and authorizes end-users. The logon module allows access to the user and administrator modules based on the role of the end-user. The logon module of the application contains the Logon.jspx, DoLogon.jspx, LogonHandler.java, and User.java files.

Creating the Logon Page

To access the online store, an end-user needs to first log on. The Logon.jspx file renders the Logon page of the application.

Listing 1-2 shows the Logon.jspx file:

Listing 1-2: The Logon.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<link rel="stylesheet" href="css/salepro.css" type="text/css"/>
</head>
<body text="#000000">
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF" size="6">
<i><center>
Online Retailer
</center></i>
</font></b></font></td>
</tr>
</table>
<!-- Display invalid logon message if authentication fails -->
<jsp:scriptlet>
if("Invalid Logon".equals(request.getParameter("error")))
{
   </jsp:scriptlet>
   <p><font color="#FF0000" face="Times New Roman, Times, serif">
   <b>Invalid Logon. Please Logon Again</b>
   </font></p>
   <jsp:scriptlet>
}
</jsp:scriptlet>
<!-- Display form to obtain logon credentials. Submit form to DoLogon.aspx -->
<form name="form1" method="post" action="DoLogon.jspx">
<table width="75%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="20%"><![CDATA[&nbsp;]]></td>
<td width="24%">
<div align="left">
<font size="3">User ID:</font>
</div>
</td>
<td width="53%"><font size="3">
<input type="text" name="textfield_logon"/>
</font>
</td>
<td width="3%">
<![CDATA[&nbsp;]]>
</td>
</tr>
<tr>
<td width="20%" height="45">
<![CDATA[&nbsp;]]>
</td>
<td width="24%" height="45">
<div align="left">
Password:
<![CDATA[&nbsp;&nbsp;&nbsp;]]>
</div>
</td>
<td width="53%" height="45">
<input type="password" name="textfield_password"/>
</td>
<td width="3%" height="45">
<![CDATA[&nbsp;]]>
</td>
</tr>
<tr>
<td width="20%">
<![CDATA[&nbsp;]]>
</td>
<td width="24%">
<div align="right">
<input type="submit" name="Submit" value="Submit" class="button"/>
</div>
</td>
<td width="53%">
<div align="left">
<input type="reset" name="Reset" value="Reset" class="button"/>
</div>
</td>
<td width="3%">
<![CDATA[&nbsp;]]>
</td>
</tr>
</table>
</form>
<p>
<![CDATA[&nbsp;]]>
</p>
<p><font size="3"></font></p>
<p>
<![CDATA[&nbsp;]]>
</p>
<p></p>
<p></p>
</body>
</html>
</jsp:root>
End example

Download this listing.

The above code creates the Logon page with the User ID and Password text boxes, the Submit button, and the Reset button.

Figure 1-2 shows the Logon page of the online retail application:

Click To expand: This figure shows the Logon page of the online retail application, which displays the User ID and Password fields in which an end-user can specify logon information.
Figure 1-2: The Logon Page

Creating the Logon Controller

The logon controller of the online retail application uses a JavaBean to authenticate logon information. The DoLogon JSP document is the logon controller of the application. DoLogon JSP authorizes end-users to access a particular module of the application and displays the user interface corresponding to the end-user role.Listing 1-3shows the DoLogon.jspx file:

Listing 1-3: The DoLogon.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<!-- Use the page directive to import packages -->
<jsp:directive.page import="salepro.*"/>
<!-- Use the JavaBean Logon handler -->
<jsp:useBean id="logonChecker" class="salepro.LogonHandler">
<jsp:scriptlet>
/*Call validateUser() method of LogonHandler bean. Pass the end-user specified user ID and
password as method argument*/
User vu =
logonChecker.validateUser(request.getParameter("textfield_logon"),request.getParameter("textfie
ld_password"));
/*Set the retrieved user object in current session*/
session.setAttribute("currentuser",vu);
/*Switch through user roles*/
switch(vu.getRole())
   {
      case 1:
      /*If role value is 1, forward to the admin page*/
      session.setAttribute("user",vu);
      </jsp:scriptlet>
      <jsp:forward page="AdminPage.jspx"/>
      <jsp:scriptlet>
      break;
      case 2:
      /*If role value is 2, forward to the user page*/
      session.setAttribute("user",vu);
      </jsp:scriptlet>
      <jsp:forward page="UserPage.jspx"/>
      <jsp:scriptlet>
      break;
      default:
      /*For other role values, forward to the login page with a parameter to indicate error*
      </jsp:scriptlet>
      <jsp:forward page="Logon.jspx">
      <jsp:param name="error" value="Invalid Logon"/>
      </jsp:forward>
      <jsp:scriptlet>
   }
</jsp:scriptlet>
</jsp:useBean>
</jsp:root>
End example

Download this listing.

The above code uses the<jsp:useBean> tag to include the LogonHandler JavaBean. The code calls the validateUser() method of the JavaBean with end-user information passed as method arguments. The code then uses the User object returned by the validateUser() method to determine the role of the end-user. The code corresponding to the end-user role forwards control to the AdminPage.jspx, UserPage.jspx, or Logon.jspx file.

Creating the LogonHandler JavaBean

The LogonHandler JavaBean of the retail application authenticates end-user information against the records stored in the database. For authenticated end-users, LogonHandler creates a User object and calls the setRole() method of the object with the value of the role retrieved from the database.Listing 1-4 shows the LogonHandler.java file:

Listing 1-4: The LogonHandler.java File
Start example
package salepro;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
public class LogonHandler
{
   User VOU;
  Connection con;
   /*Implement setUser method to set the user ID, password, and role of User object*/
   private void setUser(String StringUserID, String StringPassword)
   {
      VOU= new User();
      VOU.setUserID(StringUserID);
      VOU.setPassword(StringPassword);
      VOU.setRole(3); // 3 is unsuccessful
   }
   /*Implement validateUser method to validate a user*/
   public User validateUser(String StringUserID, String StringPassword)
   {
      /*Set user ID and password*/
      setUser(StringUserID,StringPassword);
      /*Get the role from the database and set it in the function*/
      try{
            int intRole;
            /*Obtain a connection to the data source*/
            InitialContext InitialContext_1 = new InitialContext();
            DataSource DataSource_1 = (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
            con = DataSource_1.getConnection();
            /*Create JDBC Statement object to execute SQL query*/
            Statement stmt = con.createStatement();
            /*Execute SQL query to retrieve ResultSet for end-user specified user ID and
            password*/
            ResultSet rs = stmt.executeQuery("Select * from [User] where UserID ='" +
            StringUserID
            + "' and
            Password='" + StringPassword + "'");
            /*Iterate through ResultSet*/
            if(rs.next())
            {
               /*Set User object role with role retrieved from database*/
               if(StringPassword.equals(rs.getString("Password")))
               VOU.setRole(rs.getInt("Role"));
               else
               VOU.setRole(3);
               /*Close ResutSet*/
               rs.close();
            }
            else
            {
               /*Else set 3 to indicate unauthenticated user*/
               VOU.setRole(3);
            }

         }catch(Exception e)
         {
            e.printStackTrace();
         }
         finally
           {
               /*Close connections*/
               try
               {
                   con.close();
               }
               catch(Exception ex)
               {
                  ex.printStackTrace();
               }
           }
            /*Return User object*/
            return VOU;
      }
}
End example

Download this listing.

The above code obtains end-user information as an argument of the validateUser() method. This method uses Java Naming and Directory Interface (JNDI) to locate a DataSource object and connect to the database. The method checks the end-user information against the records retrieved from the database. The method also checks the end-user role and creates a User object with the assigned role. Finally, the method returns the User object to its caller.

Creating the User Class

The User class of the retail application represents the end-user's information and role. Various components of the application use the User class to authorize an end-user and monitor the end-user during a shopping session. Listing 1-5 shows the User.java class:

Listing 1-5: The User.java Class
Start example
package salepro;
/*Class to represent an end-user*/
public class User
{
   /*Fields to store user ID, password, and role*/
   private String strUSERID;
   private String strPASSWORD;
   private int intROLE;
   /*Set the user ID for an end-user*/

   public void setUserID(String StringUserID)
   {
      strUSERID=StringUserID;
   }
   /*Retrieve user ID of an end-user*/
   public String getUserID()
   {
      return strUSERID;
   }
   /*Set the password for an end-user*/
   public void setPassword(String StringPassword)
   {
      strPASSWORD=StringPassword;
   }
   /*Retrieve the password for an end-user*/
   public String getPassword()
   {
      return strPASSWORD;
   }
   /*Set the role for an end-user*/
   public void setRole(int intRole)
   {
   intROLE=intRole;
   }
   /*Set the role for an end-user*/
   public int getRole()
   {
      return intROLE;
   }
}
End example

Download this listing.

The above code provides fields to represent an end-user's user ID, password, and role as values. The setUserID(), setPassword(), and setRole() methods store the values. The getUserID(), getPassword(), and getRole() methods return the field values to the caller of the methods.


Creating the User Module

The user module of the application allows an end-user to purchase items from the online store. The user module also allows an end-user to view the items in the store and monitor the end-user's shopping activities. The files in the user module of the application are:

  • UserPage.jspx: Renders the User Options page.

  • ViewAllItems.jspx: Renders the View All Items page.

  • PurchaseItems.jspx: Renders the Purchase Items page.

  • DoPurchase.jspx: Stores an end-user's purchase information in the database.

  • ViewTotalPurchase.jspx: Renders the View Total Purchase page.

Creating the User Options Page

The User Options page displays hyperlinks that enable an end-user to purchase and view items. The UserPage.jspx file renders the User Options page of the online retail application.

Listing 1-6 shows the UserPage.jspx file:

Listing 1-6: The UserPage.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<title>User Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
</head>
<!-- Page Design -->
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF"
size="6"><i><center>Online
Retailer</center></i></font></b></font></td>
</tr>
</table>
<body text="#000000">
<div align="center">
<p><u><b><font size="5" color="#F43700" face="Arial, Helvetica,
sans-serif">User
Options</font></b></u></p>
<p><![CDATA[&nbsp;]]></p>
<!-- Display links to ViewAllItems.jspx, PurchaseItems.jspx, ViewTotalPurchase.jspx, and
Logon.jspx pages -->
<p align="center"><b><font size="3" color="#F43700"><a
href="ViewAllItems.jspx">View Items</a></font></b></p>
<p align="center"><b><font size="3" color="#F43700"><a
href="PurchaseItems.jspx">Purchase Items</a></font></b></p>
<p align="center"><b><font size="3" color="#F43700"><a
href="ViewTotalPurchase.jspx">View Total Purchase</a></font></b></p>
<p align="center"><b><font size="3" color="#F43700"><a
href="Logon.jspx">Logout</a></font></b></p>
</div>
</body>
</html>
</jsp:root>
End example

Download this listing.

The above code creates the User Options page and displays hyperlinks to the ViewAllItems.jspx, PurchaseItems.jspx, ViewTotalPurchase.jspx, and Logon.jspx pages.

Figure 1-3 shows the User Options page of the online retail application:

Click To expand: This figure shows the User Options page that displays the View Items, Purchase Items, View Total Purchase, and Logout hyperlinks.
Figure 1-3: The User Options Page

Creating the View All Items Page

The View All Items page displays information about items present in the online store, such as item code, item name, price, and quantity. Both the user and administrator modules can access the View All Items page. The ViewAllItems.jspx file renders the View All Items page. Listing 1-7 shows the ViewAllItems.jspx file:

Listing 1-7: The ViewAllItems.jspx File
Start example

<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use page directive to import packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="salepro.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<!-- Use page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<!-- Page Design -->
</head>
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black">
<b><font color="#FFFFFF" size="6"><i>
<center>Online Retailer</center>
</i></font></b>
</font></td>
</tr>
<!-- Tabular format to display all items -->
</table>
<body >
<p></p>
<center><H3><bold>View All Items</bold></H3></center>
<p></p>
<table width="600" border="1" cellspacing="0" cellpadding="0" align="center">
<tr align="center">
<td width="7%">Sl No</td>
<td width="14%">Item Code</td>
<td width="25%">Item Name</td>
<td width="12%">Price</td>
<td width="14%">Quantity</td>
</tr>
<jsp:scriptlet>
/*Retrieve User object from session*/
User VOU = (User)session.getAttribute("currentuser");
try{
      /*Use JNDI lookup to obtain DataSource*/
      InitialContext InitialContext_1 = new InitialContext();
      DataSource DataSource_1 = (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
      /*Create connection to data source*/
      Connection con = DataSource_1.getConnection();
      /*Create Statement object to execute SQL query*/
      Statement stmt = con.createStatement();
      /*Retrieve all items as a ResultSet object*/
      ResultSet rs = stmt.executeQuery("select * from item");
      int cntr1 = 0;
      /*Iterate through ResultSet object*/
      while(rs.next())
      {
         cntr1 = cntr1 +1 ;
         String item_id=rs.getString(1);
         </jsp:scriptlet>
         <form action="UpdateItem.jspx" method="get">
         <!-- Display Items in tabular format -->
         <tr>
         <td width="7%" height="21" align="left">
         <jsp:expression>
         cntr1
         </jsp:expression>
         </td>
         <td width="14%" height="21">
         <div align="center">
         <jsp:expression>
         item_id
         </jsp:expression>
         </div>
         </td>
         <td width="25%" height="21">
         <div align="center">
         <jsp:expression>
         rs.getString(2)
         </jsp:expression>
         </div>
         </td>
         <td width="12%" height="21" align="right">
         <div align="center">
         <jsp:expression>
         rs.getString(3)
         </jsp:expression>
         </div>
         </td>
         <td width="14%" height="21" align="right">
         <div align="center">
         <jsp:expression>
         rs.getString(4)
         </jsp:expression>
         </div>
         </td>
         </tr>
         </form>
         <jsp:scriptlet>
      }
   }
   catch(Exception e)
   {
      e.printStackTrace();
   }
   </jsp:scriptlet>
   </table>
   <jsp:scriptlet>
   /*If user has administrator role, display link to AdminPage.jspx*/
   if(VOU.getRole()==1)
  {
      </jsp:scriptlet>
      <center>
      <a href="AdminPage.jspx">Go back to main menu</a>
      </center>
      <jsp:scriptlet>
  }
  else
  {
      /*If user has user role, display link to UserPage.jspx*/
      </jsp:scriptlet>
      <center>
      <a href="UserPage.jspx">Go back to main menu</a>
      </center>
      <jsp:scriptlet>
  }
</jsp:scriptlet>
</body>
</html>
</jsp:root>
End example

Download this listing.

The above code creates the View All Items page. The code uses JNDI to locate a data source and connect to the database. The code retrieves data about available items and displays the data in tabular format. Figure 1-4 shows the View All Items page of the online retail application:

Click To expand: This figure shows the View All Items page, which uses a table to display information about the items available in the store.
Figure 1-4: The View All Items Page

Creating the Purchase Items Page

An end-user can purchase items from the online store using the Purchase Items page. The end-user can specify the quantity to be purchased and click the Purchase button to record the purchase. The PurchaseItems.jspx file renders the Purchase Items page. Listing 1-8 shows the PurchaseItems.jspx file:

Listing 1-8: The PurchaseItems.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use page directive to import necessary packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="salepro.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<!-- Page Design-->
</head>
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b>
<font color="#FFFFFF" size="6"><i>
<center>Online Retailer</center>
</i></font></b>
</font></td>
</tr>
</table>
<body>
<jsp:scriptlet>
String error = request.getParameter("error");
if(error==null||"na".equals(error))
{
   </jsp:scriptlet>
   <p></p>
   <center><H3>
   <bold>Purchase Items</bold>
   </H3></center>
   <p></p>
   <center>
   <bold>Enter the quantity you want to purchase</bold>
   </center>
   <table width="600" border="1" cellspacing="0" cellpadding="0" align="center">
   <tr align="center">
   <td width="7%">Sl No</td>
   <td width="14%">Item Code</td>
   <td width="25%">Item Name</td>
   <td width="12%">Price</td>
   <td width="14%">Available Quantity</td>
   <td width="14%">Purchase Quantity</td>
   <td width="21%">Action</td>
   </tr>
   <jsp:scriptlet>
   try{
         /*Use JNDI lookup to obtain DataSource*/
         InitialContext InitialContext_1 = new InitialContext();
         DataSource DataSource_1 = (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
         /*Create connection to data source*/
         Connection con=DataSource_1.getConnection();
         Statement stmt = con.createStatement();
         /*Execute SQL statement to retrieve all items in ResultSet*/
         ResultSet rs = stmt.executeQuery("select * from item");
         int cntr1 = 0;
         /*Iterate through ResultSet*/
         while(rs.next())
         {
            cntr1 = cntr1 +1 ;
            String item_id=rs.getString(1);
            String item_name=rs.getString(2);
            String item_price=rs.getString(3);
            String item_qty=rs.getString(4);
            /*Obtain item data*/
            </jsp:scriptlet>
            <!-- Render form to display items that a user can purchase. Submit form data to
            DoPurchase.jspx -->
            <form action="DoPurchase.jspx" method="get">
            <tr>
            <!-- Use hidden form fields to track items a user purchases -->
            <input type = "hidden" name ="operation" value = "na"/>
            <!-- Display items in tabular format -->
            <td width="7%" height="21" align="left">
            <jsp:expression>cntr1</jsp:expression>
            </td>
            <td width="14%" height="21">
            <div align="center">
            <jsp:expression>item_id</jsp:expression>
            <![CDATA[ <input type = "hidden" name ="itemid" value = "]]>
            <jsp:expression>item_id</jsp:expression>
            <![CDATA[">]]>
            </div>
            </td>
            <td width="25%" height="21">
            <div align="center">
            <jsp:expression>item_name</jsp:expression>
            </div>
            </td>
            <td width="12%" height="21" align="right">
            <div align="center">
            <jsp:expression>item_price</jsp:expression>
            </div>
            </td>
            <td width="14%" height="21" align="right">
            <div align="center">
            <jsp:expression>item_qty</jsp:expression>
            <![CDATA[ <input type = "hidden" name ="itemqty" value = "]]>
            <jsp:expression>item_qty</jsp:expression>
            <![CDATA[">]]>
            </div>
            </td>
            <td width="14%">
            <input type="text" name="itempurchaseqty" class="txtbox2"/>
            </td>
            <td width="21%">
            <!-- Submit button to submit form data -->
            <input type="button"  name="btnPurchase" value="Purchase" class="smlbutton"
            onClick="{this.form.operation.value='purchase';this.form.submit();}"/>
            </td>
            </tr>
            </form>
            <jsp:scriptlet>
         }
      }
      catch(Exception e)
      {
      }
      </jsp:scriptlet>
      </table>
      <jsp:scriptlet>
}
/*If purchase fails, display error message and provide link to PurchaseItems.jspx*/
if("failedpurchase".equals(error))
{
   </jsp:scriptlet>
   <center>
   <bold>Quantity you specified is not available. Please enter lesser quantity for the
   item.</bold>
   </center>
   <center>
   <a href="PurchaseItems.jspx">Purchase more</a>
   </center>
   <jsp:scriptlet>
}
/*For valid purchase, display message to indicate that the order has been successfully placed and provide
link to PurchaseItems.jspx*/
if("purchase".equals(error))
{
   </jsp:scriptlet>
   <br/><br/>
   <center>
   <H3><bold>Your order has been successfully placed. </bold></H3>
   </center>
   <center>
   <a href="PurchaseItems.jspx">Purchase more</a>
   </center>
   <jsp:scriptlet>
}
</jsp:scriptlet>
<br/>
<center>
<a href="UserPage.jspx">Go back to main menu</a>
</center>
</body>
</html>
</jsp:root>
End example

Download this listing.

The above code creates the Purchase Items page. The code uses JNDI to locate a data source and connect to the database. The code retrieves data about available items and displays the data in tabular format. The code also displays editable text fields against each item in which an end-user can specify the quantity to be purchased. The code creates a Purchase button to make purchases, and uses hidden form fields to record the items that an end-user purchases.

Figure 1-5 shows the Purchase Items page of the online retail application:

Click To expand: This figure shows the Purchase Items page, which an end-user can use to purchase items from the online store.
Figure 1-5: The Purchase Items Page

Creating the DoPurchase JSP Document

An end-user can specify the quantity of an item on the Purchase Items page of the application. Specifying the quantity and clicking the Purchase button sends the data to the DoPurchase JSP document. This document records the purchase information of an end-user, such as the item name, the quantity, and the time of purchase, in the database. The JSP document also updates the available quantity of an item in the store after a purchase. Listing 1-9 shows the DoPurchase.jspx file:

Listing 1-9: The DoPurchase.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use the page directive to import packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="salepro.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<link rel="stylesheet" href="css/salepro.css" type="text/css"/>
</head>
<body bgcolor="#94ACBA" text="#000000">
<jsp:scriptlet>
/*Use JNDI lookup to obtain DataSource*/
InitialContext InitialContext_1 = new InitialContext();
DataSource DataSource_1 = (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
/*Create connection to data source*/
Connection con = DataSource_1.getConnection();
  try{
         /*Obtain User object from session*/
         User VOU = (User)session.getAttribute("currentuser");
         /*Create Statement object to execute SQL query*/
         Statement stmt = con.createStatement();
         /*Retrieve product information and operation to perform from HttpRequest object*/
         String item_id = request.getParameter("itemid");
         String item_qty = request.getParameter("itemqty");
         String item_purqty = request.getParameter("itempurchaseqty");
         String operation = request.getParameter("operation");
         /*Check if purchase quantity is greater then available quantity*/
         <![CDATA[if(Float.parseFloat(item_qty)<Float.parseFloat(item_purqty)) ]]>
         {
            /*If purchase quantity is greater then available quantity, mark operation as
            failed*/
            operation="failedpurchase";
         }else if(operation.equals("purchase"))
         {
            /*Insert into pitem purchase data and update item data to reflect purchase*/
            stmt.executeUpdate("insert into pitem values('"+item_id
            +"','"+VOU.getUserID()+"','"+(new java.util.Date())+"','"+item_purqty+"')");
            stmt.executeUpdate("update item set
            qty='"+(Integer.parseInt(item_qty)-Integer.parseInt(item_purqty)) +"' where itemcd =
            '"
            + item_id +"'");
            </jsp:scriptlet>
            <!-- Forward to PurchaseItems.jspx page with parameter to indicate that purchase
            is recorded-- >
            <jsp:forward page="PurchaseItems.jspx">
            <jsp:param name="error" value="purchase"/>
            </jsp:forward>
            <jsp:scriptlet>
         }

      }
      catch(SQLException SE)
      {
         SE.printStackTrace();
      }
      catch(Exception E)
      {
      E.printStackTrace();
      }
      finally
      {
         /*Close database connection*/
         con.close();
      }
      </jsp:scriptlet>
      <!-- If purchase quantity is greater then available quantity, forward to
      PurchaseItems.jspx page with parameter to indicate that purchase failed -->
      <jsp:forward page="PurchaseItems.jspx">
      <jsp:param name="error" value="failedpurchase"/>
      </jsp:forward>
      </body>
      </html>
      </jsp:root>
End example

Download this listing.

The above code uses JNDI to locate a data source and connect to the database. The code obtains data for items purchased by an end-user from the HttpRequest object and inserts the data in the PItem table of the database. The code also updates the Item table of the database with the quantity of an item after a purchase.

Creating the View Total Purchase Page

An end-user can view all purchases made from the store on the View Total Purchase page. The View Total Purchase page sorts information about all purchases according to the date and time of the purchases. The ViewTotalPurchase.jspx JSP document renders the View Total Purchase page. Listing 1-10 shows the ViewTotalPurchase.jspx file:

Listing 1-10: The ViewTotalPurchase.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use page directive to import packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<jsp:directive.page import="salepro.*"/>
<!-- Use page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<!-- Page Design -->
<link rel="stylesheet" href="css/salepro.css" type="text/css"/>
</head>
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF" size="6"><i>
<center>Online Retailer</center></i>
</font></b></font></td>
</tr>
</table>
<body >
<p></p>
<center><H3><bold>View Total Purchase</bold></H3></center>
<p></p>
<!-- Use table to display total purchase -->
<table width="600" border="1" cellspacing="0" cellpadding="0" align="center">
<tr align="center">
<td width="7%">Sl No</td>
<td width="14%">Item Code</td>
<td width="28%">User</td>
<td width="28%">Date</td>
<td width="14%">Quantity</td>
<td width="14%">Price</td>
</tr>
<jsp:scriptlet>
/*Retrieve user information stored in session*/
User VOU = (User)session.getAttribute("currentuser");
        try{
               /*Use JNDI lookup to obtain DataSource*/
               InitialContext InitialContext_1 = new InitialContext();
               DataSource DataSource_1 =
                (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
               /*Create connection to data source*/
               Connection con = DataSource_1.getConnection();
               /*Create Statement object to execute SQL query*/
               Statement stmt = con.createStatement();
               /*Retrieve product information ordered by specific user*/
               ResultSet rs = stmt.executeQuery("select
               tbl1.ItemCd,tbl1.UserID,tbl1.Date,tbl1.Qty,tbl2.Price*tbl1.Qty Price from pitem
               tbl1,item tbl2 where tbl1.userid='"+VOU.getUserID()+"' and
               tbl1.ItemCd=tbl2.ItemCd");
               int cntr1 = 0;
               /*Move through ResultSet*/
               while(rs.next())
             {
               /*Obtain order details*/
               cntr1 = cntr1 +1 ;
               String item_id=rs.getString(1);
               String user_id=rs.getString(2);
               String date=rs.getString(3);
               String qty=rs.getString(4);
               String price=rs.getString(5);
               </jsp:scriptlet>
               <!-- Display total purchase in tabular format -->
               <tr>
               <!-- Create tabular structure to display order details -->
               <td width="7%" height="21" align="left" >
               <jsp:expression>cntr1</jsp:expression></td>
               <td width="14%" height="21">
               <div align="center">
               <jsp:expression>item_id</jsp:expression>
               </div>
               </td>
               <td width="25%" height="21">
               <div align="center">
               <jsp:expression>user_id</jsp:expression>
               </div>
               </td>
               <td width="12%" height="21" align="right">
               <div align="center">
               <jsp:expression>date</jsp:expression>
               </div>
               </td>
               <td width="14%" height="21" align="right">
               <div align="center">
               <jsp:expression>qty</jsp:expression>
               </div>
               </td>
               <td width="14%" height="21" align="right">
               <div align="center">
               <jsp:expression>price</jsp:expression>
               </div>
               </td>
               </tr>
               <jsp:scriptlet>
               /*End try block and catch exception if any*/
             }
          }
        catch(Exception e)
        {
        }
         </jsp:scriptlet>
         </table>
         <!-- Display link to UserPage.jspx -->
         <center>
         <a href="UserPage.jspx">Go back to main menu</a>
         </center>
         </body>
         </html>
         </jsp:root>
End example

Download this listing.

The above code creates the View Total Purchase page. The code connects to the database, retrieves purchase records of the end-user from the PItem table, and displays the retrieved records in tabular format.

Figure 1-6 shows the View Total Purchase page of the online retail application:

Click To expand: This figure shows the View Total Purchase page that displays the purchases made by an end-user from the online store.
Figure 1-6: The View Total Purchase Page


Creating the Administrator Module

The administrator module allows the store administrator to manage the items of the store. The administrator can update item information, delete item information, and add new item information using the administrator module. The administrator can also use this module to view the sales records of the store. The files of the administrator module of the online retail application are:

  • AdminPage.jspx: Renders the Administrator Options page.

  • ManageItems.jspx: Renders the Manage Items page.

  • GetAllItems.jspx: Retrieves item information from the database.

  • AddItem.jspx: Adds item information to the database.

  • UpdateItem.jspx: Updates item information in the database.

  • ViewSales.jspx: Renders the View Sales page.

Creating the Administrator Options Page

The Administrator Options page displays hyperlinks that allow the store administrator to manage the store. AdminPage.jspx renders the Administrator Options page of the online retail application.

Listing 1-11 shows the AdminPage.jspx file:

Listing 1-11: The AdminPage.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<title>Admin Page</title>
</head>
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF" size="6"><i>
<center>Online Retailer</center>
</i></font></b></font></td>
</tr>
</table>
<body text="#000000">
<div align="center">
<p><u><b>
<font size="5" color="#F43700" face="Arial, Helvetica, sans-serif">
Administrator Options
</font></b></u></p>
<p><![CDATA[&nbsp;]]></p>
<!-- Provide links to ManageItems.jspx, ViewSales.jspx,ViewAllItems.jspx,and Logon.jspx -->
<p align="center">
<b><font size="3" color="#F43700">
<a href="ManageItems.jspx">Manage Items</a>
</font></b> </p>
<p align="center">
<b><font size="3" color="#F43700">
<a href="ViewSales.jspx">View Sales </a>
</font></b></p>
<p align="center">
<b><font size="3" color="#F43700">
<a href="ViewAllItems.jspx">View Stock </a>
</font></b></p>
<p align="center">
<b><font size="3" color="#F43700">
<a href="Logon.jspx">Logout</a>
</font></b></p>
</div>
</body>
</html>
</jsp:root>
End example

Download this listing.

The above code creates the Administrator Options page and displays hyperlinks to the ManageItems.jspx, ViewSales.jspx, ViewAllItems.jspx, and Logon.jspx files.

Figure 1-7 shows the Administrator Options page of the online retail application:

Click To expand: This figure shows the Administrator Options page that displays the Manage Items, View Sales, View Stock, and Logout hyperlinks.
Figure 1-7: The Administrator Options Page

Creating the Manage Items Page

An administrator can add records of new items to the Manage Items page of the application. The Manage Items page also allows the administrator to update records of existing items and delete items. The ManageItems.jspx JSP document uses the GetAllItems.jspx JSP document to render the Manage Items page of the application. Listing 1-12 shows the ManageItems.jspx file:

Listing 1-12: The ManageItem.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<link rel="stylesheet" href="css/salepro.css" type="text/css"/>
</head>
<body text="#000000">
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF"
size="6"><i><center>Online
Retailer</center></i></font></b></font></td>
</tr>
</table>
<br/>
<center><H3><bold>Manage Items</bold></H3></center>
<!-- Provide link to AdminPage.jspx-->
<center><a href="AdminPage.jspx">Go back to main menu</a></center>
<br/><br/>
<!-- Display GetAllItems.jspx content in IFrame -->
<iframe id="Layer1" src="GetAllItems.jspx" style="position:absolute; width:750px;
height:400px; z-index:1; left: 120px; top: 270px; background-color: #99FFCC;
layer-background-color: #99FFCC; border: 1px none #000000">
</iframe>
</body>
</html>
</jsp:root>
End example

Download this listing.

The above code uses an HTML Iframe to embed the GetAllItems.jspx JSP document.

Note

An HTML Iframe, also known as inline frame, is an HTML construct that allows you to display data in a subwindow of the browser window.

Figure 1-8 shows the Manage Items page of the online retail application:

Click To expand: This figure shows the Manage Items page of the application, which displays editable text fields to obtain records of new items and an Add Item button to add records.
Figure 1-8: The Manage Items Page

Creating the GetAllItems.jspx JSP Document

The GetAllItems.jspx JSP document displays fields to add, update, and delete item records. GetAllItems.jspx uses two HTML forms to render the user interface. The first form allows the administrator to update and delete item records. The first form submits the records to the UpdateItem.jspx JSP document. The second form of the user interface displays editable text fields to add records of new items. The second form submits the records to the AddItem.jspx JSP document.

Listing 1-13 shows the GetAllItems.jspx file:

Listing 1-13: The GetAllItems.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use page directive to import packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<jsp:directive.page import="salepro.*"/>
<!-- Use page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<link rel="stylesheet" href="css/salepro.css" type="text/css"/>
</head>
<body>
<table width="600" border="1" cellspacing="0" cellpadding="0" align="center">
<tr align="center">
<td width="7%">Sl No</td>
<td width="14%">Item Code</td>
<td width="25%">Item Name</td>
<td width="12%">Price</td>
<td width="14%">Quantity</td>
<td width="28%">Action</td>
</tr>
<jsp:scriptlet>
/*Retrieve User object from session*/
User VOU = (User)session.getAttribute("currentuser");
        try{
               /*Use JNDI lookup to obtain DataSource*/
               InitialContext InitialContext_1 = new InitialContext();
               DataSource DataSource_1 =
               (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
               /*Create connection to data source*/
               Connection con = DataSource_1.getConnection();
               /*Create Statement object to execute SQL query*/
               Statement stmt = con.createStatement();
               /*Execute SQL statement to retrieve all product details*/
               ResultSet rs = stmt.executeQuery("select * from item");
               int cntr1 = 0;
               /*Iterate through ResultSet*/
               while(rs.next())
               {
                  cntr1 = cntr1 +1 ;
                  String item_id=rs.getString(1);
                  </jsp:scriptlet>
                  <!-- Render HTML Form to display available items and to allow users to
                  update and delete items. Submit form data to UpdateItem.jspx -->
                  <form action="UpdateItem.jspx" method="get">
                  <tr>
                  <!-- Use hidden fields to track item for update and delete -->
                  <input type = "hidden" name ="operation" value = "na"/>
                  <!-- Display items in tabular format. Display item data in editable text
                  fields -->
                  <td width="7%" height="21" align="left"
                  ><jsp:expression>cntr1</jsp:expression></td>
                  <td width="14%" height="21">
                  <div align="center">
                  <jsp:expression>item_id</jsp:expression>
                  <![CDATA[ <input type = "hidden" name ="itemid" value = "]]>
                  <jsp:expression>item_id</jsp:expression>
                  <![CDATA[">]]>
                  </div>
                  </td>
                  <td width="25%" height="21">
                  <div align="center">
                  <jsp:text>
                  <![CDATA[ <input type = "text" name ="itemname" value"]]>
                  </jsp:text><jsp:expression>rs.getString(2)</jsp:expression>
                  <jsp:text><![CDATA["/>]]></jsp:text>
                  </div>
                  </td>
                  <td width="12%" height="21" align="right">
                  <div align="center">
                  <jsp:text>
                  <![CDATA[ <input type = "text" name ="itemprice" value="]]>
                  </jsp:text><jsp:expression>rs.getString(3)</jsp:expression>
                  <jsp:text><![CDATA["/>]]></jsp:text>
                  </div>
                  </td>
                  <td width="14%" height="21" align="right" >
                  <div align="center">
                  <jsp:text>
                  <![CDATA[ <input type = "text" name ="itemqty" value ="]]>
                  </jsp:text><jsp:expression>rs.getString(4)</jsp:expression>
                  <jsp:text><![CDATA["/>]]></jsp:text>
                  </div>
                  </td>
                  <td width="28%" height="21" align="center">
                  <!-- Display buttons to update and delete -->
                  <input type="button"  name="btnEdit" value="Update" class="smlbutton"
                  onClick="{this.form.operation.value='update';this.form.submit();}"/>
                  <input type="button"  name="btnDelete" value="Delete"  class="smlbutton"
                  onClick="{this.form.operation.value='delete';this.form.submit()}"/>
                  </td>
                  </tr>
                  </form>
                  <jsp:scriptlet>
               }
           }
           catch(Exception e)
           {
           }
         </jsp:scriptlet>
         <!-- Render HTML Form to display fields for adding new items. Submit form data to
         AddItem.jspx -->
         <form action="AddItem.jspx" method="post">
         <tr>
         <td width="7%" height="21" align="left">
         </td>
         <td width="14%" height="21">
         <input type="text" name ="itemid" class="txtfield2"/>
         </td>
         <td width="25%" height="21">
         <input type="text" name ="itemname"/>
         </td>
         <td width="12%" height="21">
         <input type="text" name ="itemprice"/>
         </td>
         <td width="14%" height="21">
         <input type="text" name ="itemqty"/>
         </td>
         <td width="28%" height="21">
         <input type="submit" name="btnAdd" value="Add Item" class="smlbutton"/>
         </td>
         </tr>
         </form>
         </table>
         </body>
         </html>
         </jsp:root>
End example

Download this listing.

The above code creates the GetAllItems JSP document. The code connects to the database and displays item records from the Item table. For each record, the code provides editable text fields to obtain data to update the record. The code displays the Update and Delete buttons to update and delete records. The code also displays editable text fields and an Add Item button to add records of new items.

Creating the AddItem JSP Document

When the administrator clicks the Add Item button on the Manage Items page, the records of the new item are submitted to the AddItem.jspx JSP document. The AddItem JSP document adds records of new items to the database. Listing 1-14 shows the AddItem.jspx file:

Listing 1-14: The AddItem.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use the page directive to import packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<!-- Use the page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
</head>
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF" size="6"><i>
<center>Online Retailer</center>
</i></font></b></font></td>
</tr>
</table>
<body  text="#000000">
<jsp:scriptlet>
   /*Use JNDI lookup to obtain DataSource*/
InitialContext InitialContext_1 = new InitialContext();
DataSource DataSource_1 = (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
/*Create connection to data source*/
Connection con = DataSource_1.getConnection();
  try{
         /*Create Statement object to execute SQL query*/
         Statement stmt = con.createStatement();
         /*Obtain product details to add from HttpRequest object*/
         String item_id = request.getParameter("itemid");
         String item_name = request.getParameter("itemname");
         String item_price = request.getParameter("itemprice");
         String item_qty = request.getParameter("itemqty");
         /*Execute SQL statement to insert product details to database*/
         stmt.execute("insert into item values('"+item_id+"','"+item_name
         +"','"+item_price+"','"+item_qty+"')");
         </jsp:scriptlet>
         <p></p>
         <p></p>
         <center>
         <table rows = "2" columns = "1" width="100%" border="1">
         <!-- Display message that items has been added -->
         <tr><td>
         The item
         <jsp:expression>item_name</jsp:expression>
         has been added with price :-
         <jsp:expression>item_price</jsp:expression> and quantity :-
         <jsp:expression>item_qty</jsp:expression></td></tr>
         <!-- Display link to GetAllItems.jspx-->
         <tr><td>
         <a href="GetAllItems.jspx">Go back to add more items</a>
         </td></tr>
         </table>
         </center>
         <jsp:scriptlet>
     }
     catch(SQLException SE)
     {
       SE.printStackTrace();
     }
     catch(Exception E)
     {
       E.printStackTrace();
     }
     finally
     {
       con.close();
     }
   </jsp:scriptlet>
   </body>
   </html>
   </jsp:root>
End example

Download this listing.

The above code uses the HttpRequest object to retrieve records of items in the online store. The code uses JNDI to locate the data source and create a connection to the database. The code inserts the item records in the Item table of the database. After inserting the record, the code displays a message to indicate that the record has been successfully inserted.

Creating the UpdateItem.jspx JSP Document

When the administrator clicks the Update or Delete buttons on the Manage Items page, the records of the item to be updated or deleted are submitted to the UpdateItem.jspx JSP document. The UpdateItem.jspx JSP document updates and deletes the records of items in the database.

Listing 1-15 shows the UpdateItem.jspx file:

Listing 1-15: The UpdateItem.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use page directive to import packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<!-- Use page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<!-- Page Design-->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<link rel="stylesheet" href="css/salepro.css" type="text/css"/>
</head>
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF"
size="6"><i><center>Online
Retailer</center></i></font></b></font></td>
</tr>
</table>
<body text="#000000">
<p></p>
<center><H3><bold>Update Items</bold></H3></center>
<p></p>
<jsp:scriptlet>
/*Use JNDI lookup to obtain DataSource*/
InitialContext InitialContext_1 = new InitialContext();
DataSource DataSource_1 = (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
/*Create connection to data source*/
Connection con = DataSource_1.getConnection();
try{
      /*Create Statement object to execute SQL query*/
      Statement stmt = con.createStatement();
      /*Obtain item details from HttpRequest object*/
      String item_id = request.getParameter("itemid");
      String item_name = request.getParameter("itemname");
      String item_price = request.getParameter("itemprice");
      String item_qty = request.getParameter("itemqty");
      /*Obtain operation details from HttpRequest object*/
      String operation = request.getParameter("operation");
      /*If operation is update, update database*/
      if(operation.equals("update"))
      {
         stmt.executeUpdate("update item set itemname='"+item_name +"' , price = '"+item_price+"' ,
         qty ='"+item_qty+"' where itemcd = '" + item_id +"'");
         </jsp:scriptlet>
         <!-- Page Design to specify that item information has been updated -->
         <p></p>
         <p></p>
         <center>
         <table rows = "2" columns = "1" width="100%" border="1">
         <tr><td>The item <jsp:expression>item_name</jsp:expression> has
         been updated with price :- <jsp:expression>item_price</jsp:expression> and quantity :-
         <jsp:expression>item_qty</jsp:expression></td></tr>
         <!-- Link to GetAllItems.jspx to update more items-->
         <tr><td><a href="GetAllItems.jspx">Go back to update more items
         </a></td></tr>
         </table>
         </center>
         <jsp:scriptlet>
       }
       else
       {
         /*If operation is delete, delete database records*/
         if(operation.equals("delete"))
         {
            stmt.executeUpdate("delete from item where itemcd = '" + item_id +"'");
            </jsp:scriptlet>
            <!-- Page Design to specify that item information has been deleted -->
            <p></p>
            <p></p>
            <table rows = "2" columns = "1" width="100%" border="1">
            <tr><td>The item <jsp:expression>item_name</jsp:expression>
            with price :- <jsp:expression>item_price</jsp:expression> and quantity :-
            <jsp:expression>item_qty</jsp:expression> has been
            deleted</td></tr>
            <!-- Link to GetAllItems.jspx to delete more items -->
            <tr><td><a href="GetAllItems.jspx">Go back to delete more
            items</a></td></tr>
            </table>
            <jsp:scriptlet>
         }
       }
    }
   catch(SQLException SE)
   {
   SE.printStackTrace();
   }
   catch(Exception E)
   {
   E.printStackTrace();
   }
   finally
   {
   /*Close connections*/
   con.close();
   }
   </jsp:scriptlet>
   </body>
   </html>
   </jsp:root>
End example

Download this listing.

The above code uses the HttpRequest object to obtain records of items and the delete or update operation. For the update operation, the code uses the Connection object to create a connection to the database and update the Item table with the new records. For the delete operation, the code deletes the item records from the Item table. For both operations, the code displays a message to indicate the successful completion of the operation.

Creating the View Sales Page

The View Sales page displays records of all sales made by the online store. The View Sales page displays information, such as item code, item name, and quantity sold by the store, in tabular format. The ViewSales.jspx JSP document renders the View Sales page of the application.

Listing 1-16 shows the ViewSales.jspx file:

Listing 1-16: The ViewSales.jspx File
Start example
<?xml version="1.0"?>
<!-- Namespace for the JSP document -->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Use page directive to import packages -->
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="javax.sql.*"/>
<jsp:directive.page import="javax.naming.*"/>
<!-- Use page directive to specify content type -->
<jsp:directive.page contentType="text/html"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<!-- Page Design -->
<link rel="stylesheet" href="css/salepro.css" type="text/css"/>
</head>
<table border="1" width="100%" height="100" bordercolor="#0000FF">
<tr>
<td width="100%" height="94" bordercolor="#0000FF" bgcolor="#0000FF">
<font face="Arial Black"><b><font color="#FFFFFF"
size="6"><i><center>Online
Retailer</center></i></font></b></font></td>
</tr>
</table>
<body >
<Center><H3>View Sales</H3></Center>
<br/><br/>
<!-- Use table to display sales data -->
<table width="600" border="1" cellspacing="0" cellpadding="0" align="center">
<tr align="center">
<td width="7%">Sl No</td>
<td width="14%">Item Code</td>
<td width="28%">User</td>
<td width="28%">Date</td>
<td width="14%">Quantity</td>
</tr>
<jsp:scriptlet>
try{
      /*Use JNDI lookup to obtain DataSource*/
      InitialContext InitialContext_1 = new InitialContext();
      DataSource DataSource_1 = (DataSource)InitialContext_1.lookup("jdbc/SQLResource");
      /*Create connection to data source*/
      Connection con = DataSource_1.getConnection();
      /*Create Statement object to execute SQL query*/
      Statement stmt = con.createStatement();
      /*Retrieve all data from pitem table as ResultSet object*/
      ResultSet rs = stmt.executeQuery("select * from pitem");
      int cntr1 = 0;
      /*Iterate through the ResultSet object*/
      while(rs.next())
      {
         /*Obtain sales data*/
         cntr1 = cntr1 +1 ;
         String item_id=rs.getString(1);
         String user_id=rs.getString(2);
         String date=rs.getString(3);
         String qty=rs.getString(4);
         </jsp:scriptlet>
         <!-- Display sales data in tabular format -->
         <tr>
         <td width="7%" height="21" align="left">
         <jsp:expression>cntr1</jsp:expression>
         </td>
         <td width="14%" height="21">
         <div align="center">
         <jsp:expression>item_id</jsp:expression>
         </div>
         </td>
         <td width="25%" height="21">
         <div align="center">
         <jsp:expression>user_id</jsp:expression>
         </div>
         </td>
         <td width="12%" height="21" align="right">
         <div align="center">
         <jsp:expression>date</jsp:expression>
         </div>
         </td>
         <td width="14%" height="21" align="right">
         <div align="center">
         <jsp:expression>qty</jsp:expression>
         </div>
         </td>
         </tr>
         <jsp:scriptlet>
      }
   }catch(Exception e)
   {
   }
   </jsp:scriptlet>
   </table>
   <!-- Display link to AdminPage.jspx -->
   <Center><a href="AdminPage.jspx">Go back to main menu</a></Center>
   </body>
   </html>
   </jsp:root>
End example

Download this listing.

The above code uses the Connection object to create a connection to the database, retrieve records of all sold items from PItem, and display the records in tabular format.

Figure 1-9 shows the View Sales page of the online retail application:

Click To expand: This figure shows the View Sales page of the online retail application, which displays the sales records of the store in tabular format.
Figure 1-9: The View Sales Page


Unit Testing

You can deploy and test the online retail application on Sun Java System Application Server Platform Edition 8. The steps to deploy the application are:

  1. Download this application server from:

    http://java.sun.com/j2ee/1.4/download.html

Note

To install Sun Java System Application Server Platform Edition 8, first install Java 2 Standard Edition (J2SE) 1.4.2 on your computer.

You can use the Microsoft SQL Server 2000 Driver for JDBC or MySQL Connector/J driver to connect to the Microsoft SQL Server or MySQL databases.

Note

Microsoft SQL Server 2000 Driver for JDBC is a type 4 driver that connects Java applications to Microsoft SQL Server 2000 databases.

You can download Microsoft SQL Server 2000 Driver for JDBC from: http://www.microsoft.com/sql/downloads/default.asp

  2. After you have downloaded Microsoft SQL Server 2000 Driver for JDBC, copy the driver Java Archive (JAR) files, msbase.jar, mssqlserver.jar, and msutil.jar, to the lib directory of Sun Java System Application Server. You can locate the driver JAR files in the lib directory of the driver installation directory.

  3. Finally, copy the three JAR files to the lib directory of the application server and the lib directory of the default domain of the application server.

Note

If you are using the MySQL Connector/J driver for MySQL database, copy the mysql-connector-java-3.0.14-production-bin.jar file to the lib directories of the application server.

To test the application, compile the LogonHandler.java and User.java files of your application. After compiling the files, you need to:

  1. Configure a Java Database Connectivity (JDBC) resource on the application server.

  2. Deploy the application.

  3. Test the application.

Configuring a JDBC Resource on the Application Server

The online retail application uses a JDBC resource to establish a connection with the database that stores the application data. You can create a JDBC resource using the Graphical User Interface (GUI) tool, Admin Console, of Sun Java System Application Server. To create a JDBC resource:

  1. Start the application server.

  2. Type the following URL in the address bar of the browser to open Admin Console:

                    http://localhost:4848/

  3. Log on to Admin Console with the user name and password that you specified when installing the application server. The Application Server Admin Console page appears.

  4. Expand the JDBC node in the left frame of Admin Console and select the Connection Pools hyperlink. The Connection Pools page appears in the right frame of Admin Console, as shown in Figure 1-10:

    Click To expand: This figure shows the Connection Pools page that displays the available connection pools of the application server.
    Figure 1-10: The Connection Pools Page

  5. Select the New hyperlink. The Wizard Step 1 section of the Create Connection Pool page appears. Specify SQLConnectionPool in the Name text field and select mssql from the Database Vendor drop-down list, as shown in Figure 1-11:

    Click To expand: This figure shows the Wizard Step 1 section of the Create Connection Pool page. You can specify the name of the connection pool and the database vendor for which you need to create the pool in this section.
    Figure 1-11: The Wizard Step 1 Section

  6. Select the Next hyperlink. The Wizard Step 2 section of the Create Connection Pool page appears.

  7. Type com.microsoft.jdbcx.sqlserver.SQLServerDataSource in the Data Source Class Name field.

Note

If you are using a different database, such as MySQL, you need to specify the corresponding name of the data source implementation class in the Data Source Class Name field. For MySQL 4.0, specify com.mysql.jdbc.jdbc2.optional.MysqlDataSource in the Data Source Class Name field.

  8. Select the Next hyperlink. The Wizard Step 3 section of the Create Connection Pool page appears.

  9. In the Additional Properties section of the Create Connection Pool page, specify the properties required to connect to the SQL Server 2000 database. The properties that you need to specify are:

    • DatabaseName: Name of the database that the application uses. For SQL Server 2000, specify JSPXML for this connection pool. For MySQL database, specify jdbc:mysql://localhost/JSPXML.

    • ServerName: IP address of the computer where the database is installed. If the database is installed on the local computer, you can specify localhost.

    • User: User name of the database.

    • Password: Password for the database.

  10. Click the Finish hyperlink to create the connection pool.

  11. Select the JDBC Resources hyperlink in the left frame of Admin Console. The JDBC Resources page appears.

  12. Select the New hyperlink. The Create JDBC Resource page appears.

  13. Type jdbc/SQLResource in the JNDI Name text field and select SQLConnectionPool from the Pool Name drop-down list, as shown in Figure 1-12:

    Click To expand: This figure shows the Create JDBC Resource page on which you can specify the JNDI name and a connection pool to create a JDBC resource.
    Figure 1-12: The Create JDBC Resource Page

  14. Click the OK hyperlink to create the JDBC resource.

  15. Select the Logout hyperlink to log off from Admin Console.

Deploying the Application

You can deploy the online retail application using the deploytool utility of Sun Java System Application Server. To deploy the application:

  1. Select Programs->Sun Microsystems->J2EE 1.4 SDK->Deploytool from the Start menu. The Deployment Tool window appears.

  2. Select New->Application from the File menu. The New Application dialog box appears.

  3. Click Browse in the New Application dialog box to display another New Application dialog box.

  4. Select the directory where you want to save the .ear file from the Look In combo box.

  5. Enter the name of the .ear file as OnlineRetailerAppl in the File Name text box, as shown in Figure 1-13:

    Click To expand: This figure shows the New Application dialog box in which you can specify the name and location of the application file.
    Figure 1-13: The New Application Dialog Box

  6. Click the New Application button to return to the previous New Application dialog box.

  7. Click OK to create the new application.

  8. Select New->Web Component from the File menu of the Deployment Tool window. The New Web Application Wizard-Introduction dialog box appears.

  9. Click Next. The New Web Application Wizard-WAR File dialog box appears.

  10. Click Edit Contents in the New Web Application Wizard-WAR File dialog box. The Edit Contents of WebApp dialog box appears.

  11. Select all the files of the application on the Available Files pane and click Add. The Contents of WebApp pane displays the added files, as shown in Figure 1-14:

    Click To expand: This figure shows the Edit Contents of WebApp dialog box, which displays the files of the online retail application.
    Figure 1-14: The Edit Contents of WebApp Dialog Box

  12. Click OK to add the files to the Web application's Web Archive (WAR) file.

  13. Click Next in the New Web Application Wizard-WAR File dialog box. The New Web Application Wizard-Choose Component Type dialog box appears.

  14. Select the JSP Page radio button, as shown in Figure 1-15:

    Click To expand: This figure shows the New Web Application Wizard-Choose Component Type dialog box from which you can select the component type of your Web application.
    Figure 1-15: The New Web Application Wizard-Choose Component Type Dialog Box

  15. Click Next. The New Web Application Wizard-Component General Properties dialog box appears.

  16. Select Logon.jspx from the JSP Filename drop-down list. This automatically fills the remaining fields with values. Figure 1-16 shows the New Web Application Wizard-Component General Properties dialog box:

    Click To expand: This figure shows the New Web Application Wizard-Component General Properties dialog box in which you specify the main page of your application.
    Figure 1-16: The New Web Application Wizard-Component General Properties Dialog Box

  17. Click Next. The New Web Application Wizard-Next Steps dialog box appears.

  18. Click Finish.

  19. In the Deployment Tool window, specify/first as the context root of your application in the Context Root text field, as shown in Figure 1-17:

    Click To expand: This figure shows the Context Root text field of the Deployment Tool window in which you can specify the context root of your application.
    Figure 1-17: The Deployment Tool Window

  20. Select Save from the File menu of the Deployment Tool window to save the application.

  21. Select Deploy from the Tools menu. The Deploy Module OnlineRetailerApp dialog box appears.

  22. Specify the application server's user name and password in the User Name and Password fields, and click OK. The Distribute Module dialog box appears. This dialog box indicates the successful deployment of the application, as shown in Figure 1-18:

    Click To expand: This figure shows the Distribute Module dialog box that displays a message to indicate the successful deployment of the application.
    Figure 1-18: The Distribute Module Dialog Box

Testing the Application

After deploying the application, you need to test the application. To do this:

  1. Type the following URL in the address bar of the browser:

    http://localhost:8080/first/Logon.jspx

  2. The logon page of the application appears. Specify admin in both the User ID and Password text fields, as shown in Figure 1-19:

    Click To expand: This figure shows the logon page of the application, which displays the User ID and Password fields to accept the end-user's name and password for authentication.
    Figure 1-19: Specifying the User ID and Password

  3. Click the Submit button. The Administrator Options page appears, as shown in Figure 1-20:

    Click To expand: This figure shows the Administrator Options page that displays hyperlinks to other pages of the administrator module.
    Figure 1-20: The Administrator Options Page

  4. Select the Manage Items hyperlink. The Manage Items page appears.

  5. Specify information about the item to be added, as shown in Figure 1-21:

    Click To expand: This figure shows the Manage Items page in which you can specify the records of a new item to be added.
    Figure 1-21: Specifying Information for a New Item

  6. Click the Add Item button. The Manage Items page displays a message to indicate that the item has been successfully added. The Manage Items page also displays a hyperlink to add more records.

  7. Select the Go back to add more items hyperlink to add records of other items.

  8. From the Administrator Options page, select the View Stock hyperlink. The View all Items page appears. This page displays all the available items in the store, as shown in Figure 1-22:

    Click To expand: This figure shows the View All Items page that displays records of the items available in the store.
    Figure 1-22: Items Available in the Store

  9. Select the Go back to main menu hyperlink to return to the Administrator Options page.

  10. To update and delete the names of items in the store, select the Manage Items hyperlink on the Administrator Options page. The Manage Items page displays records of available items in editable text boxes along with buttons to update and delete records. Specify new values for a record in the text field corresponding to the Price and Quantity columns, as shown in Figure 1-23:

    Click To expand: This figure shows the Manage Items page, which displays records of items in editable text boxes along with buttons to update and delete records.
    Figure 1-23: Updating Item Records

  11. Click the Update button to update a record. The Update Items page displays a message to indicate that the record has been successfully updated. You can similarly click the Delete button corresponding to a record to delete the record.

  12. On the Administrator Options page, select the Logout hyperlink to log off from the administrator module.

  13. On the Logon page, specify a user name in the User ID text field and password in the Password text field to log on to the user module. The User Options page appears, as shown in Figure 1-24:

    Click To expand: This figure shows the User Options page that displays hyperlinks to various user interfaces of the user module.
    Figure 1-24: Logging on to the User Module

  14. Select the Purchase Items hyperlink. The Purchase Items page appears. Specify the quantity that you need to purchase in the text field corresponding to the item, as shown in Figure 1-25:

    Click To expand: This figure shows the Purchase Items page, which allows end-users to purchase items from the online store.
    Figure 1-25: Specifying Purchase Quantity

  15. Click the Purchase button. A message appears indicating that the order has been successfully placed. Select the Purchase more hyperlink to purchase additional items.

  16. On the User Options page, select the View Total Purchase hyperlink. The View Total Purchase page displays records of all purchases. Figure 1-26 shows the View Total Purchase page:

    Click To expand: This figure shows the View Total Purchase page, which displays records of all purchases made by an end-user.
    Figure 1-26: Records of Purchases

  17. Select the Go back to main menu hyperlink to return to the User Options page.

  18. Select the Logout hyperlink on the User Options page to log off from the user module.


Point 2: Creating a JSP Application to Process and Transform XML Documents Using JAXP

The Java API for XML Processing (JAXP) allows you to parse and transform eXtensible Markup Language (XML) documents from JavaServer Pages (JSP) applications. JAXP provides implementation of the Document Object Model (DOM) and Simple API for XML (SAX) for parsing XML documents. DOM parses and creates an object tree of an XML document. The object tree contains nodes that represent elements of the XML document. JAXP allows you to work with the nodes of the object tree and transform the object tree back to the XML document from JSP applications.

This chapter describes how to create an online music store application that saves data in XML documents. The JSP pages of the application provide user interfaces and contain the logic to parse and transform XML documents.

Requirements of the Online Music Store Application

The online music store application allows an administrator to add or delete user login information. The administrator can also add or delete information about music and video albums from the XML documents. Application data, such as user information, album information, and album purchase information are stored in XML files. The JSP pages of the online music store application use the classes and interfaces of JAXP to read and write to the XML files. The XML files that store the application data are:

  • userlist.xml: Stores information about end users, such as user name, password, and role. An end user can have a user or administrator role.

  • musicalbumlist.xml: Stores information about music albums available in the music store.

  • videoalbumlist.xml: Stores information about video albums available in the music store.

  • musicpurchaselist.xml: Stores purchase information about music albums.

  • videopurchaselist: Stores purchase information about video albums.

The JSP pages of the application provide user interfaces that allow end users with user role to buy music albums and those with administrator role to add or delete album information. The JSP files of the online music store application are:

  • Logon.jsp: Displays text and password fields to obtain end user information.

  • DoLogon.jsp: Authenticates an end user and displays user interfaces that correspond to the end user role.

  • DoLogout.jsp: Invalidates the current session and forwards control to the Logon JSP page.

  • AdministratorPage.jsp: Displays hyperlinks to the other user interfaces of the application.

  • AddUser.jsp: Displays the fields to accept information about a new end user and records this information in the userlist.xml file.

  • AddMusicAlbum.jsp: Displays the fields to accept information about a new music album and records this information in the musicalbumlist.xml file.

  • AddVideoAlbum.jsp: Displays the fields to accept information about a new video album and records this information in the videolbumlist.xml file.

  • DeleteUser.jsp: Allows the administrator to remove information about an end user from the userlist.xml file.

  • DeleteMusicAlbum.jsp: Allows the administrator to remove information about a music album from the musicalbumlist.xml file.

  • DeleteVideoAlbum.jsp: Allows the administrator to remove information about a video album from the videoalbumlist.xml file.

  • PurchaseAlbum.jsp: Displays the user interface through which an end user can purchase music or video albums. The PurchaseAlbum.jsp page records purchase information in the musicpurchaselist.xml and videopurchaselist.xml files.

Figure 2-1 shows the architecture of the online music store application:

Click To expand: This figure shows the JSP pages the online music store application uses and the sequence in which it uses them.
Figure 2-1: Architecture of the Online Music Store Application


Creating the XML Files

The online music store application data is stored in the userlist.xml, musicalbumlist.xml, videoalbumlist.xml, musicpurchaselist.xml, and videopurchaselist.xml files.

Creating the userlist.xml File

The userlist.xml file stores end user data, such as user name, password, and role. Listing 2-1 shows the content of the userlist.xml file:

Listing 2-1: The userlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<userlist>
<user name="admin" password="admin"><role name="administrator"/>
</user>
<user name="Peter" password="peter">
<role name="user"/>
</user>
</userlist>
End example

Download this listing.

The above code uses the userlist root element to enclose the user elements. A user element contains the name and password attributes that represent the user name and password of an end user. The user element encloses a role element. The name attribute of the role element represents the role of an end user.

Creating the musicalbumlist.xml File

The musicalbumlist.xml file stores information about music albums, such as album name, group name, release date, language, and song duration. Listing 2-2 shows the musicalbumlist.xml file:

Listing 2-2: The musicalbumlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<musicalbumlist>
<album group="Symbase" name="One day in heaven" releasedon="06/06/2004">
<company language="English" length="5:35" name="Orient Group"/>
</album>
<album group="Gang of five" name="Soulless" releasedon="01/04/2004">
<company language="English" length="6:38" name="Sanguine Songs"/>
</album>
</musicalbumlist>
End example

Download this listing.

The above code uses the musicalbumlist root element to enclose the album element. The album element contains the group, name, and releasedon attributes that represent the group name, album name, and the date of release of an album. The album element encloses a company element. The company element contains the name attribute that represents the name of the company that released the album. The language and length attributes represent the language and duration of the album.

Creating the videoalbumlist.xml File

The videoalbumlist.xml file stores information about video albums, such as album name, group name, release date, language, and song duration. Listing 2-3 shows the content of the videoalbumlist.xml file:

Listing 2-3: The videoalbumlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<videoalbumlist>
<album group="Sleek band" name="Dancing in the rain" releasedon="14/02/2004">
<company language="English" length="7:10" name="Allure Music"/>
</album>
<album group="Crystal Band" name="Lift Me" releasedon="13/04/2004">
<company language="English" length="5:13" name="Sanguine Music"/>
</album>
</videoalbumlist>
End example

Download this listing.

The above code contains videoalbumlist as the root element. The album subelement of the videoalbumlist element represents a video album. The company subelement of the album element represents the name of the company that released the album.

Creating the musicpurchaselist.xml File

The musicpurchaselist.xml file stores purchase information about music albums. This file stores information, such as album name, date of purchase, and the user name of the end user who made the purchase. Listing 2-4 shows the content of the musicpurchaselist.xml file:

Listing 2-4: The musicpurchaselist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<purchaselist>
<purchase album="One day in heaven" date="Tue Jun 18 16:30:48 IST 2002" user="John"/>
<purchase album="Roaming Melodies" date="Tue Jun 18 16:33:20 IST 2002" user="John"/>
</purchaselist>
End example

Download this listing.

The above code contains the purchaselist root element that contains purchase subelements. A purchase subelement contains the album, date, and user attributes that represent the album name, date of purchase, and user name of the end user who purchased the album.

Creating the videopurchaselist.xml File

The videopurchaselist.xml file stores purchase information about video albums. Listing 2-5 shows the content of the videopurchaselist.xml file:

Listing 2-5: The videopurchaselist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<purchaselist>
<purchase album="Dancing in the rain" date="Tue Jun 18 16:33:38 IST 2002" user="John"/>
<purchase album="Lift Me" date="Tue Jun 18 16:34:27 IST 2002" user="John"/>
</purchaselist>
End example

Download this listing.

The above code contains the purchaselist root element that contains purchase subelements. The purchase subelements represent purchases made by an end user. The album, date, and user attributes of the purchase subelements represent the album name, date of purchase, and user name of the end user who purchased the album.


Creating the Logon Page

To access the online music store application, an end user needs to log on to it. The Logon page of application provides the user ID and password fields to accept end user logon information. The Logon.jsp file creates the Logon page, as shown in Listing 2-6:

Listing 2-6: The Logon.jsp File
Start example
<!-- Check HTTPRequest object for error -->
<%
String error=request.getParameter("error");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body text="#000000">
<div align="center">
<table width="767" height="80" border="3">
<tr>
<td bgcolor="#0099FF"><h2 align="center">
<font color="#FFFFFF" size="5"><strong><em>
Online Music Store </em>
</strong></font></h2></td>
</tr>
</table>
<p><font size="5">
<%
/*If HTTPRequest object contains error parameter, display error message*/
if("error".equals(error))
{
   %>
   </font></p>
   <p><font size="3">
   <strong>Invalid logon. Please try again</strong>.<center>
   <%
}
%>
</font></p>
<!-- Design HTML form to display text field for user name and password field for password.
Submit form to DoLogon.jsp-->
<form name="form1" method="post" action="DoLogon.jsp">
<table width="75%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="20%"><p>&nbsp;</p>
<p>&nbsp;</p></td>
<td width="24%" bgcolor="#FFFFFF"><div align="center"><strong>User ID:
</strong></div></td>
<td width="53%"><font size="3">
<input type="text" name="textfield_logon"/>
</font></td>
<td width="3%">&nbsp;</td>
</tr>
<tr>
<td width="20%" height="25"><p>&nbsp;</p>
<p>&nbsp;</p></td>
<td width="24%" height="25" bgcolor="#FFFFFF"><div
align="center"><strong>Password:
</strong></div></td>
<td width="53%" height="25">
<input type="password" name="textfield_password"/>
</td>
<td width="3%" height="25">&nbsp;</td>
</tr>
<tr>
<td width="20%"><p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p></td>
<td width="24%">
<div align="right">
<input type="submit" name="Submit" value="Submit" class="button"/>
</div>
</td>
<td width="53%">
<div align="left">
<input type="reset" name="Reset" value="Reset" class="button"/>
</div>
</td>
<td width="3%">&nbsp;</td>
</tr>
</table>
</form>
<p>&nbsp;</p><p><font size="3"></font></p>
<p>&nbsp;</p>
<p></p>
<p></p>
</div>
</body>
</html>
End example

Download this listing.

The above code creates the Logon page with an HTML form that contains two text fields, User ID and Password, and two buttons, Submit and Reset. This form submits data to the DoLogon.jsp page.

Figure 2-2 shows the Logon page of the online music store application:

Click To expand: This figure shows the Logon page of the online music store application that displays the User ID and Password fields in which an end user can specify logon information.
Figure 2-2: Logon Page


Creating the Logon Handler

The logon handler of the online music store application authenticates end user logon information. The logon handler compares the end user logon information with that stored in the userlist.xml file. After authentication, the logon handler displays the links to browse the music store Web site. The DoLogon.jsp file is the logon handler of the music store application. Listing 2-7 shows the content of the DoLogon.jsp file:

Listing 2-7: The DoLogon.jsp File
Start example
<!-- Use page directive to import necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*,java.io.*, java.util.*, org.w3c.dom.*"%>
<!-- Use JSP declaration to declare JSP fields-->
<%! String tempuser, temppassword, temprole, tempalbum, tempdate, userpath, videopath,
musicpath; %>
<%
/*Create a URL object to connect to userlist XML file*/
URL url=new URL("http://127.0.0.1:8080/second/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
Properties prop = new Properties();
prop.load(ucon.getInputStream());
userpath = prop.getProperty("userlistpath");
videopath = prop.getProperty("videopurchaselistpath");
musicpath = prop.getProperty("musicpurchaselistpath");
/*Create object of DocumentBuilder factory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the XML document*/
Document doc = docb.parse(new FileInputStream(userpath));
NamedNodeMap nnp;
Node n;
boolean success = false;
String userid="";
String password="";
tempuser="";
temppassword="";
temprole="";
tempalbum="";
tempdate="";
NodeList nodelist1 ;
/*Check session object for new user logon*/
if((session.getAttribute("userid"))==null)
   {
      /*Retrieve user ID and password from HttpRequest object*/
      userid=request.getParameter("textfield_logon");
      password=request.getParameter("textfield_password");
      /*Obtain a NodeList object that represents the elements of the XML file with name user*/
      nodelist1 = doc.getElementsByTagName("user");
      /*Iterate through the NodeList object*/
      for(int int_1=0;int_1 < nodelist1.getLength(); int_1 ++)
      {
         /*Retrieve NamedNodeMap object*/
         nnp=(nodelist1.item(int_1)).getAttributes();
         /*Retrieve value for user name*/
         n=nnp.getNamedItem("name");
         tempuser=(n.getNodeValue());
         /*Retrieve value for password*/
         n=nnp.getNamedItem("password");
         temppassword =(n.getNodeValue());
         /*Check retrieved user name and password values with end user specified values*/
         if(tempuser.equals(userid) && temppassword.equals(password))
         {
            /*If user name and password exists, retrieve from XML document*/
            n=nodelist1.item(int_1);
            NodeList nodelist2 = n.getChildNodes();
            n=nodelist2.item(1);
            nnp=n.getAttributes();
            n=nnp.getNamedItem("name");
            temprole=(n.getNodeValue());
            success=true;
            int_1=nodelist1.getLength();
         }
      }
   }
  else
  /*If user already exists, retrieve user id and role from session object*/
   {
      success=true;
      tempuser=(String)session.getAttribute("userid");
      temprole=(String)session.getAttribute("role");
      userid=tempuser;
   }
   /*Store user name and password in session after successful authentication*/
   if (success==true)
{
   session.setAttribute("userid", tempuser);
   session.setAttribute("role", temprole);
   %>
   <html>
   <head>
   <meta http-equiv="Content-Language" content="en-us">
   <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
   <title>Online Shopping Store</title>
   </head>
   <body>
   <table width="767" height="80" border="3">
   <tr>
   <td bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
   size="5"><strong><em>Online Music Store
   </em></strong></font></h2></td>
   </tr>
   </table>
   <table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
   <tr>
   <td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
   color="#000000"><b>User </b></font></div></td>
   <td width="104" bgcolor="#0099FF" height="1"><div
   align="center"><%=tempuser%></div></td>
   </tr>
   <tr>
   <td width="95" bgcolor="#0099FF" height="13"><div
   align="center"><b>Role</b></div></td>
   <td width="104" bgcolor="#0099FF" height="13"><div
   align="center"><%=temprole%></div></td>
   </tr>
   </table>
   <p>&nbsp;</p>
   <p>&nbsp;</p>
   <p>&nbsp;</p>
   <p>&nbsp;</p>
   <p>
   </p>
   <!-- Page Design -->
   <div align="justify"></div>
   <div align="justify">
   <table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
   left: 516px; top: 96px; width: 253px" >
   <tr>
   <!-- Display Logout hyperlink -->
   <td height="18" bgcolor="#0099FF"><div align="center"><font
   color="#FFFFFF"><b><a
   href="DoLogout.jsp">Logout</a></b></font></div></td>
   </tr>
   <tr>
   <td height="18" bgcolor="#0099FF"><div align="center"><b>
   <%if("administrator".equals(temprole))
   {%>
   <!-- For administrator role, set hyperlink to AdministratorPage.jsp -->
   <a href="AdministratorPage.jsp">
   <%}
   else
   {%>
   <!-- For userrole, set hyperlink to UserPage.jsp -->
   <a href="PurchaseAlbum.jsp">
   <%}%>
   Go to main page</a></b></div></td>
   </tr>
   </table>
   </div>
   <%
   if(!("administrator".equals(temprole)))
   {
      /*For user role, retrieve videopurchaselist.xml document*/
      /*Parse the xml document*/
      /*Create object of DocumentBuilder factory, using newInstance() method of
      DocumentBuilderFactory*/
      docbfact = DocumentBuilderFactory.newInstance();
      /*Create object of DocumentBuilder using the newDocumentBuilder() method of
      DocumentBuilderFactory*/
      docb = docbfact.newDocumentBuilder();
      /*Parse the XML document*/
      doc = docb.parse(new FileInputStream(videopath));
      /*Obtain the NodeList object for the purchase element*/
      nodelist1 = doc.getElementsByTagName("purchase");
      %>
      <!-- Page Design to display purchase details of video album in tabular format -->
      <br>
      <div align="justify">
      <table border="1" width="300" style="position: absolute; left: 439px; top: 196px"
      cellpadding="0" cellspacing="0">
      <tr>
      <td colspan="3">
      <p align="center"><b><font color="#800000">Video albums
      purchased</font></b></p>
      </td>
      </tr>
      <tr>
      <td width="40" bgcolor="#0099FF"><div align="center"><b><i><font
      color="#000000">Sl No</font></i></b></div></td>
      <td width="222" bgcolor="#0099FF"><div align="center"><b><i><font
      color="#000000">Album</font></i></b></div></td>
      <td width="130" bgcolor="#0099FF"><div align="center"><b><i><font
      color="#000000">Date</font></i></b></div></td>
      </tr>
      <%
      /*Iterate through the NodeList object*/
      for(int int_1=0,int_cntr=0;int_1 < nodelist1.getLength(); int_1 ++)
      {
         /*Retrieve nodes for user, album, and date and obtain their values*/
         nnp=(nodelist1.item(int_1)).getAttributes();
         n=nnp.getNamedItem("user");
         tempuser=(n.getNodeValue());
         n=nnp.getNamedItem("album");
         tempalbum =(n.getNodeValue());
         n=nnp.getNamedItem("date");
         tempdate =(n.getNodeValue());
         if(tempuser.equals(userid))
         {
            int_cntr = int_cntr + 1;
            %>
            <!-- Page Design to display  album, and date values in tabular format -->
            <tr>
            <td width="40"><div align="center"><%=(int_cntr)%>
            </div></td>
            <td width="222"><div
            align="center"><%=tempalbum%></div></td>
            <td width="130"><div
            align="center"><%=tempdate%></div></td>
            </tr>
            <%
         }
      }
      %>
      </table>
      </div>
      <%
      /*Create a DocumentBuilder object*/
      docb = docbfact.newDocumentBuilder();
      /*Parse the xml document*/
      doc = docb.parse(new FileInputStream(musicpath));
      /*Obtain the NodeList object for the purchase element*/
      nodelist1 = doc.getElementsByTagName("purchase");
      %>
      <!-- Page Design to display purchase details in tabular format -->
      <br>
      <div align="justify">
      <table border="1" width="300" style="position: absolute; left: 44px; top: 198px"
      cellpadding="0" cellspacing="0">
      <tr>
      <td colspan="3">
      <p align="center"><b><font color="#800000">Music albums
      purchased</font></b></p>
      </td>
      </tr>
      <tr>
      <td width="40" bgcolor="#0099FF"><div
      align="center"><b><i><font
      color="#000000">Sl No</font></i></b></div></td>
      <td width="222" bgcolor="#0099FF"><div
      align="center"><b><i><font
      color="#000000">Music Album</font></i></b></div></td>
      <td width="130" bgcolor="#0099FF"><div
      align="center"><b><i><font
      color="#000000">Date</font></i></b></div></td>
      </tr>
      <%
      /*Iterate through the NodeList object*/
      for(int int_1=0,int_cntr=0;int_1 < nodelist1.getLength(); int_1 ++)
      {
         /*Retrieve nodes for user, album, and date and obtain their values*/
         nnp=(nodelist1.item(int_1)).getAttributes();
         n=nnp.getNamedItem("user");
         tempuser=(n.getNodeValue());
         n=nnp.getNamedItem("album");
         tempalbum =(n.getNodeValue());
         n=nnp.getNamedItem("date");
         tempdate =(n.getNodeValue());
         if(tempuser.equals(userid))
         {
            int_cntr = int_cntr + 1;
            %>
            <!-- Page Design to display  album and date values in tabular format -->
            <tr>
            <td width="40"><div align="center"><%=(int_cntr)%>
            </div></td>
            <td width="222"><div
            align="center"><%=tempalbum%></div></td>
            <td width="130"><div
            align="center"><%=tempdate%></div></td>
            </tr>
            <%
         }
      }
      %>
      </table>
      </div>
      <%
   }
   %>
   </body>
   </html>
   <%
}
else
{
   /*For authentication error, forward to Logon.jsp page with error parameter*/
   %>
   <jsp:forward page="Logon.jsp">
   <jsp:param name="error" value="error"></jsp:param>
   </jsp:forward>
   <%
}
%>
End example

Download this listing.

The above code uses the HttpRequest object to obtain end user logon information. The code compares the logon information with that stored in the userlist.xml file. To do this, the code uses DOM to obtain a DocumentBuilder object. The code parses the userlist.xml file using the parse() method of the DocumentBuilder object. After parsing the XML document, the code obtains the Document object that represents the userlist.xml file as an object tree in the memory. The code iterates through the nodes of the object tree to authenticate the logon information. After authentication, the code retrieves the role assigned to the end user. If the end user is assigned the administrator role, the code displays a hyperlink to the AdministratorPage.jsp file. If the end user is assigned the user role, the code parses the musicpurchaselist.xml and videopurchaselist.xml files to display the albums purchased by the end user.

Figure 2-3 shows the user interface the DoLogon page provides when an end user with the administrator role logs on:

Click To expand: This figure shows the user interface of the DoLogon.jsp file when an administrator logs on. The user interface displays the user name and role along with the Logout and Go to main page hyperlinks.
Figure 2-3: User Interface of the DoLogon Page for Administrator Role

Figure 2-4 shows the user interface the DoLogon page provides when an end user with user role logs on:

Click To expand: This figure shows the user interface of the DoLogon.jsp file, which appears when an end user with user role logs on.
Figure 2-4: User Interface of the DoLogon Page for User Role

The user interface displays the user name and role along with the Logout and Go to main page hyperlinks. The user interface also displays a table that lists information about albums purchased by the end user.


Creating the Logout Page

When an end user selects the Logout hyperlink in the user interfaces of the online music store application, the Logout page appears. This page terminates the current session and forwards the request object to the Logon page. The following code shows the content of the Logout.jsp file:

<%
/*Invalidate current session*/
session.setAttribute("userid","");
session.setAttribute("role","");
session.invalidate();
%>
<!--Forward request to Logon.jsp page-->
<jsp:forward page="Logon.jsp"/>


Creating the Administrator Options Page

The Administrator Options page contains various hyperlinks. The AdministratorPage.jsp page provides the Administrator Options page of the online music store application.

Listing 2-8 shows the contents of the AdministratorPage.jsp file:

Listing 2-8: The AdministratorPage.jsp File
Start example
<!-- Administrator Options page that displays link to other pages of the administrator module
-->
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Administrator Options</title>
</head>
<body>
<table width="767" height="80" border="3">
<tr>
<td bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
size="5"><strong><em>Online Music Store
</em></strong></font></h2></td>
</tr>
</table>
<p ><b><font face="Arial" size="5"
color="#FFFFFF">AdministratorAdministratorAdministrator</font><font face="Arial"
size="5" color="#0000FF">Administrator
Options</font></b></p>
<!-- Retrieve user name and role from session and display it in tabular format -->
<table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
color="#000000"><b>User </b></font></div></td>
<td width="104" bgcolor="#0099FF" height="1">
<%=session.getAttribute("userid")%></td>
</tr>
<tr>
<td width="95" bgcolor="#0099FF" height="13"><div align="center"><b><font
color="#000000">Role</font></b></div></td>
<td width="104" bgcolor="#0099FF"
height="13"><%=session.getAttribute("role")%></td>
</tr>
</table>
<!-- Display hyperlink to DoLogout JSP page -->
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 530px; top: 152px; width: 232px" >
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<!-- Check current role and display the Go to main page hyperlink accordingly -->
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="PurchaseAlbum.jsp">
<%}%>
Go to main page</a></b></div></td>
</tr>
</table>
</div>
<!-- Display hyperlinks to other pages of the application -->
<p align="center">&nbsp;</p>
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 9px; top: 266px; width: 300">
<tr>
<td bgcolor="#0099FF">
<p align="center"><b><font color="#333333">Administer User
</font></b></p>
</td>
</tr>
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="AddUser.jsp">Add user</a></b></i></div></td>
</tr>
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="DeleteUser.jsp">Delete user</a></b></i></div></td>
</tr>
</table>
</div>
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 477px; top: 263px; width: 300">
<tr>
<td bgcolor="#0099FF"><p align="center"><b><font color="#000000">
Administer Album </font></b></p>
</td>
</tr>
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="AddMusicAlbum.jsp">Add music album
</a></b></i></div></td>
</tr>
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="DeleteMusicAlbum.jsp">Delete music album
</a></b></i></div></td>
</tr>
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="AddVideoAlbum.jsp">Add video album
</a></b></i></div></td>
</tr>
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="DeleteVideoAlbum.jsp">Delete video lbum
</a></b></i></div></td>
</tr>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>
</body>
</html>
End example

Download this listing.

The above code creates the Administrator Options page. This code displays links to the AddUser.jsp, DeleteUser.jsp, AddMusicAlbum.jsp, DeleteMusicAlbum.jsp, AddVideoAlbum.jsp, and DeleteVideoAlbum.jsp files.

Figure 2-5 shows the Administrator Options page:

Click To expand: This figure shows the Administrator Options page of the online music store that displays the Add user, Delete user, Add music album, Delete music album, Add video album, and Delete video album hyperlinks.
Figure 2-5: Administrator Options Page


Creating the Add New User Page

An administrator can add end user information, such as logon ID, password, and role, in the Add New User page. This page provides text fields to accept end user information. The page also displays existing user information from the userlist.xml file. The AddUser JSP provides the Add New User page.

Listing 2-9 shows the contents of the AddUser.jsp file:

Listing 2-9: The AddUser.jsp File
Start example
<!-- Import the necessary packages -->
<%@page import="javax.xml.parsers.*,java.net.*,java.io.*,org.w3c.dom.*,java.util.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory,
javax.xml.transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException,javax.xml.transform.dom.DOMSource
,javax.xml.transform.stream.St
reamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%! String path;%>
<%
/*Create a URL object to connect to load properties file*/
URL url=new URL("http://127.0.0.1:8080/second/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Retrieve the userlistpath property*/
Properties prop = new Properties();
prop.load(ucon.getInputStream());
path = prop.getProperty("userlistpath");
/*Retrieve user name, password, and role from HttpRequest object*/
String tempuser, temppassword, temprole;
tempuser=request.getParameter("txtfielduser");
temppassword=request.getParameter("txtpassword");
temprole=request.getParameter("txtrole");
/*Check if value is specified for all the three name, password, and role*/
if(!(tempuser == null || temppassword == null ||temprole == null))
{
   /*Create a DocumentBuilderFactory object*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Create a DocumentBuilder object*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the userlist.xml file*/
   Document doc = docb.parse(new FileInputStream(path));
   /*Obtain root element of XML document*/
   Element doce = doc.getDocumentElement();
   /*Create a new user element*/
   Element newe = doc.createElement("user");
   /*Set the name and password attributes of the user element, with values end user specified values*/
   newe.setAttribute("name",tempuser);
   newe.setAttribute("password",temppassword);
   /*Create a role element*/
   Element newe1 = doc.createElement("role");
   /*Set the name attribute for the role element*/
   newe1.setAttribute("name",temprole);
   /*Append role element in user element*/
   newe.appendChild(newe1);
   /*Append user element in root element*/
   doce.appendChild(newe);
   /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
   TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Specify the source of the transformation*/
   DOMSource source = new DOMSource(doc);
   /*Create the StreamResult holder for transformation to the userlist.xml file*/
   StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(path)));
   /*Perform the transformation*/
   transformer.transform(source, result);
}
%>
<!-- Page design to display Add New User page -->
<table width="830" height="71" border="3">
<tr>
<td width="816" height="61" bgcolor="#0099FF"><h2 align="center"><font
color="#FFFFFF" size="5"><strong><em>Online Music
Store </em></strong></font></h2></td>
</tr>
</table>
<!-- Retrieve user name and role from session and display it in tabular format -->
<table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
color="#333333"><b>User </b></font></div></td>
<td width="104" bgcolor="#0099FF" height="1">
<%=session.getAttribute("userid")%></td>
</tr>
<tr>
<td width="95" bgcolor="#0099FF" height="13"><div align="center"><b><font
color="#333333">Role</font></b></div></td>
<td width="104" bgcolor="#0099FF"
height="13"><%=session.getAttribute("role")%></td>
</tr>
</table>
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 620px; top: 97px;
width: 224px; height: 41px;" >
<tr>
<!-- Display hyperlink to DoLogout page -->
<td height="18" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<tr>
<!-- Check current role and display the Go to main page hyperlink accordingly -->
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="UserPage.jsp">
<%}%>
Go to main page</a></b></div></td>
</tr>
</table>
<h2 align="center">&nbsp; </h2>
<h2 align="center">Add New User </h2>
</div>
<!--Display HTML form with text fields to obtain User Name, Password, and Role. Submit Form
details to same page-->
<form action = AddUser.jsp method ="post">
<center><table width="336">
<tr>
<td width="180" bgcolor="#0099FF"><div align="center"><strong><font
color="#333333">User Name</font></strong></div></td>
<td width="144" bgcolor="#008080">
<input name="txtfielduser" ></input></td>
</tr>
<tr>
<td width="180" bgcolor="#0099FF"><div
align="center"><strong>Password</strong></div></td>
<td width="144" bgcolor="#008080">
<input name="txtpassword" type="password"></td>
</tr>
<tr>
<td width="180" bgcolor="#0099FF"><div
align="center"><strong>Role</strong></div></td>
<td width="144" bgcolor="#008080">
<input name="txtrole" ></td>
</tr><tr>
<td width="180"></input></td>
</tr>
</table></center>
<p>
<center><input type="submit" value="Add User">
</center>
</p>
</form>
<!--Page design to display available users and roles assigned o them-->
<center>
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 145px; top: 465px">
<tr bgcolor="#0099FF">
<td colspan="2">
<p align="center"><i><font color="#FFFFFF"> <strong>List of Existing
Users</strong></font></i></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b>&nbsp;User</b></font></div></td>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b>Role</b></font></div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the XML document*/
Document doc = docb.parse(new FileInputStream(path));
/*Obtain a NodeList object that represents the elements of the XML file with name user*/
NodeList nl1 = doc.getElementsByTagName("user");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object by calling the item() method of NodeList*/
   Node n=nl1.item(int_1);
   /*Obtain the NamedNodeMap object*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <!--Retrieve the name attribute value of the user element of the XML file, and display it -->
   <tr>
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("name")).getNodeValue()%></div></td>
   <%
   /*Obtain the NodeLIst object for the sub element of User element*/
   NodeList nl2 = n.getChildNodes();
   /*Obtain the attributes for the sub element as NamedNodeMap object*/
   Node n2=nl2.item(1);
   NamedNodeMap nnp1 = n2.getAttributes();
   %>
   <!--Retrieve the name attribute value of the role sub element of the XML file, and display it-->
   <td width="147" bgcolor="#FFFFFF"><div
  align="center"><%=(nnp1.getNamedItem("name")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
</center>
</div>
<p>&nbsp;</p>
<p>&nbsp;</p></html>
End example

Download this listing.

The above code creates the Add New User page that contains an HTML form with text fields to accept end user information. This code also displays the existing end user information that is stored in the userlist.xml file. The code uses DOM to parse the userlist.xml file and retrieve all end user information stored in that file. When an administrator specifies information about a new end user and clicks the Add User button, the code uses the HttpRequest object to obtain the end user information. The code uses DOM to create an object tree of the userlist.xml file. The code then adds a new node to the object tree. This new node represents the end user information that needs to be added. Finally, the code uses the javax.xml.transform.Transformer object to transform the updated object tree into the userlist XML document.

Figure 2-6 shows the Add New User page of the online music store application:

Click To expand: This figure shows the Add New User page that displays information about existing users and provides fields to add new user information.
Figure 2-6: Add New User Page


Creating the Delete User Page

The Delete User page displays a drop-down list that contains the user names of all the existing end users. A store administrator can select a user name from this list and delete its corresponding information. The DeleteUser JSP file provides the Delete User page, as shown in Listing 2-10:

Listing 2-10: The DeleteUser.jsp File
Start example
<!--
JSP Page that allows an end user to delete end user information
-->
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%><%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory,
javax.xml.transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException, javax.xml.transform.dom.
DOMSource, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%! String path;%>
<%
   /*Create a URL object to load properties file*/
   URL url=new URL("http://127.0.0.1:8080/second/path.properties");
   /*Open URL connection*/
   URLConnection ucon=url.openConnection();
   /*Retrieve userlistpath property*/
   Properties prop = new Properties();
   prop.load(ucon.getInputStream());
   path = prop.getProperty("userlistpath");
   String tempuser;
   /*Retrieve user name to delete from HttpRequest object*/
   tempuser=request.getParameter("txtfielduser");
   /*Check if user name to delete is present*/
   if(!(tempuser == null ))
   {
      /*Create object of DocumentBuildeFactory, using newInstance() method of DocumentBuilderFactory*/
      DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
      /*Create object of DocumentBuilder using the newDocumentBuilder() method of DocumentBuilderFactory*/
      DocumentBuilder docb = docbfact.newDocumentBuilder();
      /*Parse musicpurchaselist.xml and obtain a Document object*/
      Document doc = docb.parse(new FileInputStream(path));
      /*retrieve NodeList object corresponding to user element*/
      NodeList nluserlist = doc.getElementsByTagName("userlist");
      /*Retrieve NodeList for child elements*/
      Node doce = nluserlist.item(0);
      NodeList nl1 = doce.getChildNodes();
      /*Iterate through the NodeList object*/
      for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
      {
         /*Check for the user element*/
         Node n = nl1.item(int_1);
         if((n.getNodeName()).equals("user"))
         {
         /*Retrieve value of name attribute for the user element*/
            NamedNodeMap nnp= n.getAttributes();
            String tempuser2=(nnp.getNamedItem("name")).getNodeValue();
            /*Check retrieved value with end user specified value to delete*/
            if(tempuser.equals(tempuser2))
            {
               /*Delete element from XML file*/
               doce.removeChild(n);
            }
         }
      }
   /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
   TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Specify the source of the transformation*/
   DOMSource source = new DOMSource(doc);
   /*Create the StreamResult holder for transformation to the musicpurchaselist.xml file*/
   StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(path)));
   /*Perform the transformation*/
   transformer.transform(source, result);
}
%>
<!--Page design to display Delete User page-->
<table width="767" height="80" border="3">
<tr>
<td bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
size="5"><strong><em>Online Music Store
</em></strong></font></h2></td>
</tr>
</table>
<!--Retrieve user name and role from session and display it in tabular format-->
<p align="center"><font size="5"><b>Delete User
</b></font></p>
<table width="215" height="1" border="0" cellpadding="0" cellspacing="0"
bgcolor="#0099FF">
<tr>
<td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
color="#000000"><b>User </b></font></div></td>
<td width="104" bgcolor="#0099FF" height="1">
<div align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
<tr>
<td width="95" bgcolor="#0099FF" height="13"><div
align="center"><b>Role</b></div></td>
<td width="104" bgcolor="#0099FF" height="13"><div
align="center"><%=session.getAttribute("role")%></div></td>
</tr>
</table>
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 530px; top: 152px;
width: 232px" >
<tr>
<!--Display hyperlink to DoLogout page-->
<td height="18" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<tr>
<!--Check current role and display the Go to main page hyperlink accordingly-->
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="PurchaseItem.jsp">
<%}%>
Go to Main Page</a></b></div></td>
</tr>
</table>
</div>
<!--Display HTML form with drop-down option field to obtain information on user to delete.
Submit Form details to same page-->
<form action = DeleteUser.jsp method ="post">
<table width="507">
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><font
color="#333333"><strong>Select User
Name</strong></font></div></td>
<td width="153" bgcolor="#FFFFFF"><select name="txtfielduser">
<option value=""></option>
<%
/*Create object of DocumentBuildeFactory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse musicpurchaselist.xml and obtain a Document object*/
Document doc = docb.parse(new FileInputStream(path));
/*Obtain a NodeList object that represents the elements of the XML file with name user*/
NodeList nl1 = doc.getElementsByTagName("user");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Retrieve NamedNodeMap that represents attributes of the user element*/
   Node n=nl1.item(int_1);
   NamedNodeMap nnp = n.getAttributes();
   %>
   <option
 value=<%=(nnp.getNamedItem("name")).getNodeValue()%>><%=(nnp.getNamedItem("name"))
 .getNodeValue()%></option>
  <%
}
%>
</select></td>
<!--Populate drop-down list with attribute values-->
<td width="153" bgcolor="#FFFFFF"><input type="submit" value="Delete
User"></td>
</tr>
<tr>
<td width="179"></input></td>
</tr>
</table>
</form>
<div align="justify">
<!--Page design to display users in tabular format-->
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 147px; top: 284px">
<tr bgcolor="#0099FF">
<td colspan="2">
<p align="center"> <font color="#000000"><b>Existing
Users</b></font></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#000000"><b>&nbsp;User</b></font></div></td>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#000000"><b>Role</b></font></div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
docb = docbfact.newDocumentBuilder();
/*Parse the XML document, userlist.xml to retrieve the Document object*/
doc = docb.parse(new FileInputStream(path));
/*Obtain a NodeList object that represents the elements of the XML file with name user*/
nl1 = doc.getElementsByTagName("user");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object by calling the item() method of NodeList*/
   Node n=nl1.item(int_1);
   /*Obtain the NamedNodeMap object that represents the attributes of the album element*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <tr>
   <!--Retrieve the name attribute value of the album element of the XML file, and display it -->
   <td width="147" bgcolor="#FFFFFF"><div
 align="center"><%=(nnp.getNamedItem("name")).getNodeValue()%></div></td>
   <%
   /*Obtain the NodeLIst object for the sub element company of album element*/
   NodeList nl2 = n.getChildNodes();
   /*Obtain the attributes for the sub element as NamedNodeMap object*/
   Node n2=nl2.item(1);
   NamedNodeMap nnp1 = n2.getAttributes();
   %>
   <!--Retrieve the name attribute value of the company sub element of the XML file, and display it -->
   <td width="147" bgcolor="#FFFFFF"><div
 align="center"><%=(nnp1.getNamedItem("name")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>
</html>
End example

Download this listing.

The above code creates the Delete User page. This code displays a drop-down list and populates it with the existing user names that are stored in the userlist.xml file. The code parses the userlist.xml file and iterates through its nodes to retrieve all user name values. The code also displays information about existing users in tabular format. When an administrator selects a user name from the drop-down list and clicks the Delete User button, the code creates an object tree of the userlist.xml document. The code then locates the node of the object tree that corresponds to the end user name to be deleted. The code removes the node from the object tree and uses a Transformer object to transform the updated object tree to the userlist XML document.

Figure 2-7 shows the Delete User page of the online music store application:

Click To expand: This figure shows the Delete User page that displays a drop-down list and a Delete User button. The Delete User page also displays information about existing end users.
Figure 2-7: Delete User Page


Creating the Add Music Album Page

An administrator can use the Add Music Album page to store data about new music albums in the musicalbumlist.xml file. The Add Music Album page also displays information about music albums available in the store. The AddMusicAlbum.jsp file creates the Add Music Album page, as shown in Listing 2-11:

Listing 2-11: The AddMusicAlbum.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory,
javax.xml.transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException, javax.xml.transform.dom.
DOMSource, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%! String musicpath;%>
<%
/*Create a URL object to load the properties file*/
URL url=new URL("http://127.0.0.1:8080/second/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Retrieve the musicalbumlistpath property*/
Properties prop = new Properties();
prop.load(ucon.getInputStream());
musicpath = prop.getProperty("musicalbumlistpath");
/*Retrieve album name, group name, release date, company name, language, and length information
from HttpRequest object*/
String tempalbum,tempgroup,tempreleasedon,tempcompany,templanguage,templength;
tempalbum=request.getParameter("txtalbum");
tempgroup=request.getParameter("txtgroup");
tempreleasedon=request.getParameter("txtreleasedon");
tempcompany=request.getParameter("txtcompany");
templanguage=request.getParameter("txtlanguage");
templength=request.getParameter("txtlength");
/*Check whether all information to add music album are specified*/
if(!(tempalbum == null || tempgroup == null ||tempreleasedon == null ||tempcompany == null ||
templanguage == null ||templength == null))
{
   /*Create object of DocumentBuildeFactory, using newInstance() method of
   DocumentBuilderFactory*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Create object of DocumentBuilder using the newDocumentBuilder() method of
   DocumentBuilderFactory*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the musicalbumlist.xml document and obtain a Document object*/
   Document doc = docb.parse(new FileInputStream(musicpath));
   /*Obtain Element object that represents root element of XML document*/
   Element doce = doc.getDocumentElement();
   /*Create a new element, album*/
   Element newe = doc.createElement("album");
   /*Set the name, group, and releaseon attributes of the album element with end user specified
   values*/
   newe.setAttribute("name", tempalbum);
   newe.setAttribute("group", tempgroup);
   newe.setAttribute("releasedon", tempreleasedon);
   /*Create a new element, company*/
   Element newe1 = doc.createElement("company");
   /*Set the name, language, and length attributes of the company element with end user specified values*/
   newe1.setAttribute("name", tempcompany);
   newe1.setAttribute("language", templanguage);
   newe1.setAttribute("length", templength);
   /*Append company element in album element*/
   newe.appendChild(newe1);
   /*Append album element in root element*/
   doce.appendChild(newe);
   /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
   TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Specify the source of the transformation*/
   DOMSource source = new DOMSource(doc);
   /*Create the StreamResult holder for transformation to the musicalbumlist.xml file*/
   StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(musicpath)));
   /*Perform the transformation*/
   transformer.transform(source, result);
}
%>
<!--Page design to display Add Music Album page-->
<table width="767" height="80" border="3">
<tr>
<td bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
size="5"><strong><em>Online Music Store
</em></strong></font></h2></td>
</tr>
</table>
<h2><font color="#000000"><strong><font
color="#FFFFFF">iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii</font>Add Music
Album</strong></font></h2>
<!--Retrieve user name and role from session and display it in tabular format-->
<table border="1" width="273" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="99" bgcolor="#0099FF" height="1"><div align="center"><font
color="#000000"><strong>User</strong> </font></div></td>
<td width="168" bgcolor="#0099FF" height="1">
<%=session.getAttribute("userid")%></td>
</tr>
<tr>
<td width="99" bgcolor="#0099FF" height="13"><div align="center"><b><font
color="#000000">Role</font></b></div></td>
<td width="168" bgcolor="#0099FF"
height="13"><%=session.getAttribute("role")%></td>
</tr>
</table>
<!--Display hyperlink to DoLogout page-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 413px; top: 154px; width: 334px; height: 40px;">
<tr>
<td height="26" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<tr>
<!--Check current role and display the Go to main page hyperlink accordingly-->
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="UserPage.jsp">
<%}%>
Go to main page</a></b></div></td>
</tr>
</table>
</div>
<!--Display HTML form with text fields to obtain information on album name, group name,
release date, company name, language, and song duration. Submit Form details to same page-->
<form action = AddMusicAlbum.jsp method ="post">
<table width="657">
<tr>
<td width="225" bgcolor="#CCCCCC"><div align="center"><font
color="#0000FF"><strong>Album Name</strong></font></div></td>
<td width="420" bgcolor="#00CCFF">
<input name="txtalbum" size="70">
</input></td>
</tr>
<tr>
<td width="225" bgcolor="#CCCCCC"><div align="center"><font
color="#0000FF"><strong>Group Name</strong></font></div></td>
<td width="420" bgcolor="#008080">
<input name="txtgroup" size="70"></td>
</tr>
<tr>
<td width="225" bgcolor="#CCCCCC"><div align="center"><strong><font
color="#0000FF">Release Date</font> </strong></div></td>
<td width="420" bgcolor="#008080">
<input name="txtreleasedon" size="70" ></td>
</tr>
<tr>
<td width="225" bgcolor="#CCCCCC"><div align="center"><strong><font
color="#0000FF">Music Company</font></strong></div></td>
<td width="420" bgcolor="#008080">
<input name="txtcompany" size="70" ></td>
</tr>
<tr>
<td width="225" bgcolor="#CCCCCC"><div align="center"><strong><font
color="#0000FF">Language</font></strong></div></td>
<td width="420" bgcolor="#008080">
<input name="txtlanguage" size="70"></td>
</tr>
<tr>
<td width="225" bgcolor="#CCCCCC"><div align="center"><strong><font
color="#0000FF">Song Duration </font></strong></div></td>
<td width="420" bgcolor="#008080">
<input name="txtlength" size="70" ></td>
</tr>
</table>
<br>
<center>
<input type="submit" value="Add Music Album">
</center>
</form>
<!--Page design to display available music albums-->
<div align="center">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 75px; top: 498px; width: 681px; background-color: #0000FF; layer-background-color:
#0000FF; border: 1px none #000000;">
<tr bgcolor="#0033FF">
<td colspan="2"><h2 align="center"><i><font color="#FFFFFF"><b>
Existing Albums</b></font></i></h2>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="right">
<h3 align="center"><font color="#333333"><b>&nbsp; Album Name
</b></font></h3>
</div></td>
<td width="147" bgcolor="#0099FF"><div align="right">
<h3 align="center"><font color="#000000"><b> Company Name
</b></font></h3>
</div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the XML document, videoalbumlist.xml to retrieve the Document object*/
Document doc = docb.parse(new FileInputStream(musicpath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
NodeList nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object by calling the item() method of NodeList*/
   Node n=nl1.item(int_1);
   /*Obtain the NamedNodeMap object that represents the attributes of the album element*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <tr>
   <!--Retrieve the name attribute value of the album element of the XML file, and display it -->
   <td width="147"
   bgcolor="#FFFFFF"><%=(nnp.getNamedItem("name")).getNodeValue()%></td>
   <%
   /*Obtain the NodeLIst object for the sub element company of album element*/
   NodeList nl2 = n.getChildNodes();
   /*Obtain the attributes for the sub element as NamedNodeMap object*/
   Node n2=nl2.item(1);
   NamedNodeMap nnp1 = n2.getAttributes();
   %>
   <!--Retrieve the name attribute value of the company sub element of the XML file, and
   display it-->
   <td width="147"
   bgcolor="#FFFFFF"><%=(nnp1.getNamedItem("name")).getNodeValue()%></td>
   </tr>
   <%
}
%>
</table>
</div>
</html>
End example

Download this listing.

The above code creates the Add Music Album page of the online music store application. The code provides text fields to obtain information about the music album to be added. The Add Music Album button submits the information to the AddMusicAlbum JSP page. When an administrator clicks the Add Music Album button, the code uses the HttpRequest object to obtain information about the album to be added. The code then loads the musicalbumlist.xml file and parses it using the parse() method. The parse() method returns a Document object that represents an object tree of the XML document. The code uses the createElement() method to create a new node that corresponds to the information about the new album. Finally, the code transforms the object tree back to the musicalbumlist XML document. Figure 2-8 shows the Add Music Album page of the online music store application:

Click To expand: This figure shows the Add Music Album page of the online music store application that displays the fields in which an administrator can specify information to add a music album.
Figure 2-8: Add Music Album Page


Creating the Delete Music Album Page

The Delete Music Album page allows an administrator to delete information about a music album stored in the musicalbumlist.xml file. The Delete Music Album page displays a drop-down list from which an administrator can select the name of an album to be deleted. The Delete Music Album page also displays data for the music albums available in the store. The DeleteMusicAlbum.jsp file provides the Delete Music Album page, as shown in Listing 2-12:

Listing 2-12: The DeleteMusicAlbum.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*,java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory,
javax.xml.transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException,
javax.xml.transform.dom.DOMSource, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%! String musicpath;%>
<%
/*Create a URL object to load the properties file*/
URL url=new URL("http://127.0.0.1:8080/second/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Retrieve the musicalbumlistpath*/ property
Properties prop = new Properties();
prop.load(ucon.getInputStream());
musicpath = prop.getProperty("musicalbumlistpath");
/*Retrieve album name to delete from HttpRequest object*/
String tempuser;
tempuser=request.getParameter("txtfieldalbum");
/*Check if album name to delete is provided*/
if(!(tempuser == null ))
{
   /*Create object of DocumentBuildeFactory, using newInstance() method of
   DocumentBuilderFactory*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Create object of DocumentBuilder using the newDocumentBuilder() method of
   DocumentBuilderFactory*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse musicpurchaselist.xml and obtain a Document object*/
   Document doc = docb.parse(new FileInputStream(musicpath));
   /*retrieve NodeList object corresponding to musicalbumlist element*/
   NodeList nluserlist = doc.getElementsByTagName("musicalbumlist");
   /*Retrieve NodeList for child elements*/
   Node doce = nluserlist.item(0);
   NodeList nl1 = doce.getChildNodes();
   /*Iterate through the NodeList object*/
   for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
   {
      /*Check for the album element*/
      Node n = nl1.item(int_1);
      if((n.getNodeName()).equals("album"))
      {
         /*Retrieve value of name attribute for the album element*/
         NamedNodeMap nnp= n.getAttributes();
         String tempuser2=(nnp.getNamedItem("name")).getNodeValue();
         /*Check retrieved value with end user specified value to delete*/
         if(tempuser.equals(tempuser2))
         {
            /*Delete element from XML file*/
            doce.removeChild(n);
         }
      }
   }
   /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
    TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Specify the source of the transformation*/
   DOMSource source = new DOMSource(doc);
   /*Create the StreamResult holder for transformation to the musicpurchaselist.xml file*/
   StreamResult result = new StreamResult(new PrintStream(new   FileOutputStream(musicpath)));
   /*Perform the transformation*/
   transformer.transform(source, result);
}
%>
<!--Page design to display Delete Music Album page-->
<table width="767" height="80" border="3">
<tr>
<td bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
size="5"><strong><em>Online Music Store
</em></strong></font></h2></td>
</tr>
</table>
<p align="center"><font size="5"><b>Delete Album
</b></font></p>
<!--Retrieve user name and role from session and display it in tabular format-->
<table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
color="#333333"><b>User </b></font></div></td>
<td width="104" bgcolor="#0099FF" height="1">
<%=session.getAttribute("userid")%></td>
</tr>
<tr>
<td width="95" bgcolor="#0099FF" height="13"><div
align="center"><b>Role</b></div></td>
<td width="104" bgcolor="#0099FF"
height="13"><%=session.getAttribute("role")%></td>
</tr>
</table>
<!--Display hyperlink to DoLogout page-->
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 532px; top: 157px;
width: 220px" >
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<tr>
<!--Check current role and display the Go to main page hyperlink accordingly-->
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="PurchaseAlbum.jsp">
<%}%>
Go to Main Page</a></b></div></td>
</tr>
</table>
</div>
<!--Display HTML form with drop-down option field to obtain information on album to delete.
Submit Form details to same page-->
<form action = DeleteMusicAlbum.jsp method ="post">
<table width="507">
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Select Music
Album Name</strong> </div></td>
<td width="153" bgcolor="#FFFFFF"><select name="txtfieldalbum">
<option value=""></option>
<%
/*Create object of DocumentBuildeFactory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse musicpurchaselist.xml and obtain a Document object*/
Document doc = docb.parse(new FileInputStream(musicpath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
NodeList nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Retrieve NamedNodeMap that represents attributes of the album element*/
   Node n=nl1.item(int_1);
   NamedNodeMap nnp = n.getAttributes();
   %>
   /*Populate drop-down list with attribute values*/
   <option
value=<%=(nnp.getNamedItem("name")).getNodeValue()%>><%=(nnp.getNamedItem("name"))
.getNodeValue()%></option>
   <%
}
%>
</select></td>
<td width="153" bgcolor="#FFFFFF"><input type="submit" value="Delete
Album"></td>
</tr>
<tr>
<td width="179"></input></td>
</tr>
</table>
</form>
<!--Page design to display available music albums in tabular format-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 163px; top: 316px">
<tr bgcolor="#0099FF">
<td colspan="2">
<p align="center"><font color="#333333"> <strong> Available Music
Albums</strong></font></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#000000"><b>&nbsp;Album Name</b></font></div></td>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#333333"><b> Company Name </b></font></div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
docb = docbfact.newDocumentBuilder();
/*Parse the XML document, musicalbumlist.xml to retrieve the Document object*/
doc = docb.parse(new FileInputStream(musicpath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
/*Obtain the Node object by calling the item() method of NodeList*/
Node n=nl1.item(int_1);
/*Obtain the NamedNodeMap object that represents the attributes of the album element*/
NamedNodeMap nnp = n.getAttributes();
%>
<tr>
<!--Retrieve the name attribute value of the album element of the XML file, and display it -->
<td width="147" bgcolor="#FFFFFF"><div
align="center"><%=(nnp.getNamedItem("name")).getNodeValue()%></div></td>
<%
/*Obtain the NodeLIst object for the sub element company of album element*/
NodeList nl2 = n.getChildNodes();
/*Obtain the attributes for the sub element as NamedNodeMap object*/
Node n2=nl2.item(1);
NamedNodeMap nnp1 = n2.getAttributes();
%>
<!--Retrieve the name attribute value of the company sub element of the XML file, and display it -->
<td width="147" bgcolor="#FFFFFF"><div
align="center"><%=(nnp1.getNamedItem("name")).getNodeValue()%></div></td>
</tr>
<%
}
%>
</table>
<p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
</div></html>
End example

Download this listing.

The above code creates the Delete Music Album page of the online music store application. This page contains a drop-down list and a Delete Album button. The code parses the musicalbumlist.xml file and iterates through its nodes to retrieve the names of all the music albums in the file. The code then populates the drop-down list with the album names it retrieved from the musicalbumlist.xml file. When an end user with administrator role selects an album name and clicks the Delete Album button, the code creates an object tree of the musicalbumlist XML document and removes the node that corresponds to that album name from the tree. The code then transforms the object tree back to the musicalbumlist XML document. The code also parses the musicalbumlist.xml file to retrieve information about available albums and displays them in tabular format.

Figure 2-9 shows the Delete Music Album page of the online music store application:

Click To expand: This figure shows the Delete Music Album page of the online music store application that contains a drop-down list and a Delete Album button. This page also displays information about available music albums.
Figure 2-9: Delete Music Album Page


Creating the Add Video Album Page

An administrator can use the Add Video Album page to add information about new video albums in the videoalbumlist.xml file. The Add Video Album page contains various text fields and an Add Video Album button. This page also displays information about all video albums present in the store. The AddVideoAlbum.jsp file provides the Add Video Album page, as shown in Listing 2-13:

Listing 2-13: The AddVideoAlbum.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory,
javax.xml.transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException, javax.xml.transform.dom.DOMSource
, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%!String videopath;%>
<%
/*Create a URL object to connect to userlist XML file*/
URL url=new URL("http://127.0.0.1:8080/second/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
Properties prop = new Properties();
prop.load(ucon.getInputStream());
videopath = prop.getProperty("videoalbumlistpath");
/*Retrieve album name, group name, release date, company name, language, and length information
from HttpRequest object*/
String tempalbum,tempgroup,tempreleasedon,tempcompany,templanguage,templength;
tempalbum=request.getParameter("txtalbum");
tempgroup=request.getParameter("txtgroup");
tempreleasedon=request.getParameter("txtreleasedon");
tempcompany=request.getParameter("txtcompany");
templanguage=request.getParameter("txtlanguage");
templength=request.getParameter("txtlength");
/*Check whether all information to add video album are specified*/
if(!(tempalbum == null || tempgroup == null ||tempreleasedon == null ||tempcompany == null ||
templanguage == null ||templength == null))
{
   /*Create object of DocumentBuildeFactory, using newInstance() method of
   DocumentBuilderFactory*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Create object of DocumentBuilder using the newDocumentBuilder() method of
   DocumentBuilderFactory*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the videoalbumlist.xml document and obtain a Document object*/
   Document doc = docb.parse(new FileInputStream(videopath));
   /*Obtain Element object the represents root element of XML document*/
   Element doce = doc.getDocumentElement();
   /*Create a new element, album*/
   Element newe = doc.createElement("album");
   /*Set the name, group, and releaseon attributes of the album element with end user specified values*/
   newe.setAttribute("name", tempalbum);
   newe.setAttribute("group", tempgroup);
   newe.setAttribute("releasedon", tempreleasedon);
   /*Create a new element, company*/
   Element newe1 = doc.createElement("company");
   /*Set the name,language, and length attributes of the company element with end user specified
   values*/
   newe1.setAttribute("name", tempcompany);
   newe1.setAttribute("language", templanguage);
   newe1.setAttribute("length", templength);
   /*Append company element in album element*/
   newe.appendChild(newe1);
   /*Append album element in root element*/
   doce.appendChild(newe);
   /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
   TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Specify the source of the transformation*/
   DOMSource source = new DOMSource(doc);
   /*Create the StreamResult holder for transformation to the videoalbumlist.xml file*/
   StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(videopath)));
   /*Perform the transformation*/
   transformer.transform(source, result);
}
%>
<!--Page design to display Add Video Album page-->
<table width="857" height="80" border="3">
<tr>
<td width="1205" bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
size="5"><strong><em>Online Music Store
</em></strong></font></h2></td>
</tr>
</table>
<p align="center"><font size="5"><b>Add Video Album
</b></font></p>
<!--Retrieve user name and role from session and display it in tabular format-->
<table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
color="#000000"><b>User </b></font></div></td>
<td width="104" bgcolor="#0099FF" height="1">
<div align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
<tr>
<td width="95" bgcolor="#0099FF" height="13"><div
align="center"><b>Role</b></div></td>
<td width="104" bgcolor="#0099FF" height="13"><div
align="center"><%=session.getAttribute("role")%></div></td>
</tr>
</table>
<!--Display hyperlink to DoLogout page-->
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute; left: 604px; top: 152px;
width: 234px">
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<tr>
<!--Check current role and display the Go to main page hyperlink accordingly-->
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="UserPage.jsp">
<%}%>
Go to main page</a></b></div></td>
</tr>
</table>
</div>
<!--Display HTML form with text fields to obtain information on album name, group name,
release date, company name, language,
and song duration. Submit Form details to same page-->
<form action = AddVideoAlbum.jsp method ="post">
<center><table width="346">
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Album
Name</strong></div></td>
<td width="153" bgcolor="#FFFFFF">
<input name="txtalbum" ></input></td>
</tr>
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Group
Name</strong></div></td>
<td width="153" bgcolor="#FFFFFF">
<input name="txtgroup" ></td>
</tr>
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Release
Date</strong></div></td>
<td width="153" bgcolor="#FFFFFF">
<input name="txtreleasedon" ></td>
</tr>
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Company Name
</strong></div></td>
<td width="153" bgcolor="#FFFFFF">
<input name="txtcompany" ></td>
</tr>
<tr>
<td width="179" bgcolor="#0099FF"><div
align="center"><strong>Language</strong></div></td>
<td width="153" bgcolor="#FFFFFF">
<input name="txtlanguage" ></td>
</tr>
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Song Duration
</strong></div></td>
<td width="153" bgcolor="#FFFFFF">
<input name="txtlength" ></td>
</tr>
<tr>
<td width="179"></input></td>
</tr>
</table>
<input type="submit" value="Add Video Album">
</center>
</form>
<!--Page design to display available video albums-->
<center>
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 213px; top: 439px; width:
385px;">
<tr bgcolor="#0099FF">
<td colspan="2">
<p align="center"><font color="#333333"><b> Existing Video
Albums</b></font></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#333333"><b>&nbsp;Album</b></font></div></td>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#333333"><b> Company Name </b></font></div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the XML document, videoalbumlist.xml to retrieve the Document object*/
Document doc = docb.parse(new FileInputStream(videopath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
NodeList nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object by calling the item() method of NodeList*/
   Node n=nl1.item(int_1);
   /*Obtain the NamedNodeMap object that represents the attributes of the album element*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <!--Retrieve the name attribute value of the album element of the XML file, and display it -->
   <tr>
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("name")).getNodeValue()%></div></td>
   <%
   /*Obtain the NodeLIst object for the sub element company of album element*/
   NodeList nl2 = n.getChildNodes();
   /*Obtain the attributes for the sub element as NamedNodeMap object*/
   Node n2=nl2.item(1);
   NamedNodeMap nnp1 = n2.getAttributes();
   %>
   <!--Retrieve the name attribute value of the company sub element of the XML file, and display it -->
   <td width="147" bgcolor="#FFFFFF"><div
  align="center"><%=(nnp1.getNamedItem("name")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
</center>
<p>
<p></html>
End example

Download this listing.

The above code creates the Add Video Album page that contains text fields and an Add Video Album button to add information about new video albums. This code also displays information about all the video albums stored in the videoalbumlist.xml file. To retrieve and display information about a video album, the code uses DOM to parse the videoalbumlist.xml file. When an administrator specifies information about a new video album and clicks the Add Video Album button, the code uses DOM to create an object tree of the videoalbumlist XML document. The code adds a new node to the object tree that corresponds to the specified information. Finally, the code transforms the updated object tree into the videoalbumlist XML document.

Figure 2-10 shows the Add Video Album page of the online music store application:

Click To expand: This figure shows the Add Video Album page of the online music store application that contains text fields and the Add Video Album button.
Figure 2-10: Add Video Album Page


Creating the Delete Video Album Page

An administrator can use the Delete Video Album page to delete information about a video album. This page contains a video album name drop-down list and a Delete Video Album button. The page also displays information about video albums stored in the videoalbumlist.xml file. The DeleteVideoAlbum.jsp file provides the Delete Video Album page of the application, as shown in Listing 2-14:

Listing 2-14: The DeleteVideoAlbum.jsp File
Start example
<!--
JSP Page that allows an end user to delete a video album
-->
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory, javax.xml.transf
orm.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException,javax.xml.transform.dom.DOMSource
,javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%!String videopath;%>
<%
/*Create a URL object to load properties file*/
URL url=new URL("http://127.0.0.1:8080/second/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Retrieve videoalbumlistpath property*/
Properties prop = new Properties();
prop.load(ucon.getInputStream());
videopath = prop.getProperty("videoalbumlistpath");
/*Retrieve album name to delete from HttpRequest object*/
String tempuser;
tempuser=request.getParameter("txtfieldalbum");
/*Check if album name to delete is provided*/
if(!(tempuser == null ))
{
   /*Create object of DocumentBuildeFactory, using newInstance() method of
   DocumentBuilderFactory*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Create object of DocumentBuilder using the newDocumentBuilder() method of
   DocumentBuilderFactory*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse musicpurchaselist.xml and obtain a Document object*/
   Document doc = docb.parse(new FileInputStream(videopath));
   /*retrieve NodeList object corresponding to musicalbumlist element*/
   NodeList nluserlist = doc.getElementsByTagName("videoalbumlist");
   /*Retrieve NodeList for child elements*/
   Node doce = nluserlist.item(0);
   NodeList nl1 = doce.getChildNodes();
   /*Iterate through the NodeList object*/
   for(int int_1 = 0; int_1< nl1.getLength(); int_1 ++)
   {
      /*Check for the album element*/
      Node n = nl1.item(int_1);
      if((n.getNodeName()).equals("album"))
      {
         /*Retrieve value of name attribute for the album element*/
         NamedNodeMap nnp= n.getAttributes();
         String tempuser2=(nnp.getNamedItem("name")).getNodeValue();
         /*Check retrieved value with end user specified value to delete*/
         if(tempuser.equals(tempuser2))
         {
            /*Delete element from XML file*/
            doce.removeChild(n);
         }
      }
   }
   /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
   TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Specify the source of the transformation*/
   DOMSource source = new DOMSource(doc);
   /*Create the StreamResult holder for transformation to the videoalbumlist.xml file*/
   StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(videopath)));
   /*Perform the transformation*/
   transformer.transform(source, result);
}
%>
<!--Page design to display Delete Video Album page-->
<table width="767" height="80" border="3">
<tr>
<td bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
size="5"><strong><em>Online Music Store
</em></strong></font></h2></td>
</tr>
</table>
<p align="center"><font size="5"><b>Delete Video Album
</b></font></p>
<!--Retrieve user name and role from session and display it in tabular format-->
<table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
color="#000000"><b>User </b></font></div></td>
<td width="104" bgcolor="#0099FF" height="1">
<div align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
<tr>
<td width="95" bgcolor="#0099FF" height="13"><div
align="center"><b>Role</b></div></td>
<td width="104" bgcolor="#0099FF" height="13"><div
align="center"><%=session.getAttribute("role")%></div></td>
</tr>
</table>
<!--Display hyperlink to DoLogout page-->
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 496px; top: 154px; width: 266px" >
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
 </tr>
<!--Check current role and display the Go to main page hyperlink accordingly-->
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="PurchaseItem.jsp">
<%}%>
Go to main page</a></b></div></td>
</tr>
</table>
</div>
<!--Display HTML form with drop-down option field to obtain information on album to delete.
Submit Form details to same page-->
<form action = DeleteVideoAlbum.jsp method ="post">
<Center>
<table width="507">
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Select Video
Album Name</strong></div></td>
<td width="153" bgcolor="#FFFFFF"><select name="txtfieldalbum">
<option value=""></option>
<%
/*Create object of DocumentBuildeFactory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse videoalbumlist.xml and obtain a Document object*/
Document doc = docb.parse(new FileInputStream(videopath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
NodeList nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1<nl1.getLength(); int_1 ++)
{
  /*Retrieve NamedNodeMap that represents attributes of the album element*/
   Node n=nl1.item(int_1);
   NamedNodeMap nnp = n.getAttributes();
   %>
   /*Populate drop-down list with attribute values*/
   <option
 value=<%=(nnp.getNamedItem("name")).getNodeValue()%>><%=(nnp.getNamedItem("name"))
 .getNodeValue()%></option>
   <%
}
%>
</select></td>
<td width="153" bgcolor="#FFFFFF"><input type="submit" value="Delete Video
Album"></td>
</tr>
<tr>
<td width="179"></input></td>
</tr>
</table>
</Center>
</form>
<!--Page design to display available video albums in tabular format-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 202px; top: 312px">
<tr bgcolor="#0099FF">
<td colspan="2">
<p align="center">  <font color="#000000"><b>Available Video
Albums</b></font></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#333333"><b>&nbsp;Album Name</b></font></div></td>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#000000"><b>Company Name</b></font></div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of DocumentBuilderFactory*/
docb = docbfact.newDocumentBuilder();
/*Parse the XML document, videoalbumlist.xml to retrieve the Document object*/
doc = docb.parse(new FileInputStream(videopath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 <nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object by calling the item() method of NodeList*/
   Node n=nl1.item(int_1);
   /*Obtain the NamedNodeMap object that represents the attributes of the album element*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <!--Retrieve the name attribute value of the album element of the XML file, and display it -->
   <tr>
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("name")).getNodeValue()%></div></td>
   <%
   /*Obtain the NodeLIst object for the sub element company of album element*/
   NodeList nl2 = n.getChildNodes();
   /*Obtain the attributes for the sub element as NamedNodeMap object*/
   Node n2=nl2.item(1);
   NamedNodeMap nnp1 = n2.getAttributes();
   %>
   <!--Retrieve the name attribute value of the company sub element of the XML file, and
   display it -->
   <td width="147" bgcolor="#FFFFFF"><div
  align="center"><%=(nnp1.getNamedItem("name")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div></html>
End example

Download this listing.

The above code creates the Delete Video Album page of the online music store application. This page displays a drop-down list and a Delete Video Album button. The code populates the drop-down list with the names retrieved from the videoalbumlist.xml file after parsing the file. When an end user clicks the Delete Video Album button, the code uses DOM to parse the videoalbumlist XML document to create an object tree. The code iterates through the object tree to locate the node that corresponds to the video album name to be deleted. After locating the node, the code removes it from the object tree and transforms the object tree back to the videoalbumlist XML document.

Figure 2-11 shows the Delete Video Album page of the online music store application:

Click To expand: This figure shows the Delete Video Album page of the online music store application that contains a drop-down list and a Delete Video Album button. It also displays a table that provides information about the video albums available in the store.
Figure 2-11: Delete Video Album Page


Creating the Purchase Album Page

The Purchase Album page of the online music store application displays the fields in which an end user can specify information to purchase albums. The Purchase Album page stores purchase information in the musicpurchaselist.xml and videopurchaselist.xml files. The PurchaseAlbum.jsp file provides the Purchase Album page, as shown in Listing 2-15:

Listing 2-15: The PurchaseAlbum.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory,
javax.xml.transf
orm.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException, javax.xml.transform.dom.DOMSource
, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys, java.util.Vector"%>
<%!String videopath, musicpath, videopurchasepath, musicpurchasepath; %>
<%
/*Create a URL object to load properties file*/
URL url=new URL("http://127.0.0.1:8080/second/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Retrieve the videoalbumlistpath,musicalbumlistpath,videopurchaselistpath, and musicpurchaselistpath
properties*/
Properties prop = new Properties();
prop.load(ucon.getInputStream());
videopath = prop.getProperty("videoalbumlistpath");
musicpath = prop.getProperty("musicalbumlistpath");
videopurchasepath = prop.getProperty("videopurchaselistpath");
musicpurchasepath = prop.getProperty("musicpurchaselistpath");
%>
<%
/*Retrieve album type and album name information from HttpRequest object*/
String tempalbum,tempalbumtype,tempuser;
tempalbumtype=request.getParameter("txtalbumtype");
tempalbum=request.getParameter("txtalbum");
/*Retrieve user name from current session*/
tempuser=(String)session.getAttribute("userid");
/*Check if purchase information and user name exists*/
if(!(tempalbum == null || tempuser== null || tempalbumtype==null))
{
   /*Create object of DocumentBuildeFactory, using newInstance() method of
   DocumentBuilderFactory*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Create object of DocumentBuilder using the newDocumentBuilder() method of
   DocumentBuilderFactory*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Check If album type for purchase is music*/
   if(tempalbumtype.equals("music"))
   {
       /*Parse musicpurchaselist.xml and obtain a Document object*/
      Document doc = docb.parse(new FileInputStream(musicpurchasepath));
      /*Obtain Element object that represents root element of XML document*/
      Element doce = doc.getDocumentElement();
      /*Create a new element purchase*/
      Element newe = doc.createElement("purchase");
      /*Set user, album, and date atrributes*/
      newe.setAttribute("user",tempuser);
      newe.setAttribute("album",tempalbum);
      newe.setAttribute("date",""+(new java.util.Date()));
      /*Append purchase element to root element*/
      doce.appendChild(newe);
      /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
      TransformerFactory tFactory = TransformerFactory.newInstance();
      /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
      Transformer transformer = tFactory.newTransformer();
      /*Set output property of Transformer object*/
      transformer.setOutputProperty(OutputKeys.INDENT,"yes");
      /*Specify the source of the transformation*/
      DOMSource source = new DOMSource(doc);
      /*Create the StreamResult holder for transformation to the musicpurchaseist.xml file*/
      StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(musicpurchasepath)));
      /*Perform the transformation*/
      transformer.transform(source, result);
   }
   /*Check If album type for purchase is video*/
   if(tempalbumtype.equals("video"))
   {
      Document doc = docb.parse(new FileInputStream(videopurchasepath));
      /*Obtain Element object that represents root element of XML document*/
      Element doce = doc.getDocumentElement();
      /*Create a new element purchase*/
      Element newe = doc.createElement("purchase");
      /*Set user, album, and date atrributes*/
      newe.setAttribute("user",tempuser);
      newe.setAttribute("album",tempalbum);
      newe.setAttribute("date",""+(new java.util.Date()));
      /*Append purchase element to root element*/
      doce.appendChild(newe);
      /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
      TransformerFactory tFactory = TransformerFactory.newInstance();
      /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
      Transformer transformer = tFactory.newTransformer();
      /*Set output property of Transformer object*/
      transformer.setOutputProperty(OutputKeys.INDENT,"yes");
      /*Specify the source of the transformation*/
      DOMSource source = new DOMSource(doc);
      /*Create the StreamResult holder for transformation to the videopurchaselist.xml file*/
      StreamResult result = new StreamResult(new PrintStream(new
      FileOutputStream(videopurchasepath)));
      /*Perform the transformation*/
      transformer.transform(source, result);
   }
}
%>
<!--Page design to display Purchase Album page-->
<table width="767" height="80" border="3">
<tr>
<td bgcolor="#0099FF"><h2 align="center"><font color="#FFFFFF"
size="5"><strong><em>Online Music Store
</em></strong></font></h2></td>
</tr>
</table>
<!--Retrieve user name and role from session and display it in tabular format-->
<table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="95" bgcolor="#0099FF" height="1"><div align="center"><font
color="#000000"><b>User </b></font></div></td>
<td width="104" bgcolor="#0099FF" height="1"><div
align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
<tr>
<td width="95" bgcolor="#0099FF" height="13"><div
align="center"><b>Role</b></div></td>
<td width="104" bgcolor="#0099FF" height="13"><div
align="center"><%=session.getAttribute("role")%></div></td>
</tr>
</table>
<font size="5"><b>Purchase Album </b></font>
<!--Display hyperlink to DoLogout page-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 493px; top: 92px;
width: 286px" >
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<!--Check current role and display the Go to main page hyperlink accordingly-->
<tr>
<td height="18" bgcolor="#0099FF"><div align="center"><b>
<%if("administrator".equals(session.getAttribute("role")))
{%>
<a href="AdministratorPage.jsp">
<%}
else
{%>
<a href="DoLogon.jsp">
<%}%>
Go to main page</a></b></div></td>
</tr>
</table>
</div>
<!--Display HTML form with fields to obtain information on album purchase. Submit Form
details to same page-->
<form action = PurchaseAlbum.jsp method ="get">
<table width="507">
<tr>
<td width="179" bgcolor="#0099FF"><div align="center"><strong>Select
Album</strong> </div></td>
<td width="153" bgcolor="#FFFFFF"><select name="txtalbumtype"">
<option value="music">MUSIC</option>
<option value="video">VIDEO</option>
</select>
<input name="txtalbum" ></td>
<td width="153" bgcolor="#FFFFFF"></input>
<input type="submit" value="Purchase Album"></td>
</tr>
<tr>
<td width="179"></input></td>
</tr>
</table>
</form>
<!--Page design to display available music albums in tabular format-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 30; top: 350">
<tr bgcolor="#0099FF">
<td colspan="2">
<p align="center"><font color="#000000"><b> Available Music
Albums</b></font></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#000000"><b> Album Name </b></font></div></td>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#000000"><b> Company Name </b></font></div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the XML document, musicalbumlist.xml to retrieve the Document object*/
Document doc = docb.parse(new FileInputStream(musicpath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
NodeList nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object by calling the item() method of NodeList*/
   Node n=nl1.item(int_1);
   /*Obtain the NamedNodeMap object that represents the attributes of the album element*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <tr>
   <!--Retrieve the name attribute value of the album element of the XML file, and display it -->
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("name")).getNodeValue()%></div></td>
   <%
   /*Obtain the NodeLIst object for the sub element company of album element*/
   NodeList nl2 = n.getChildNodes();
   /*Obtain the attributes for the sub element as NamedNodeMap object*/
   Node n2=nl2.item(1);
   NamedNodeMap nnp1 = n2.getAttributes();
   %>
   <!--Retrieve the name attribute value of the company sub element of the XML file, and
   display it -->
   <td width="147" bgcolor="#FFFFFF"><div
  align="center"><%=(nnp1.getNamedItem("name")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
</div>
<!--Page design to display available music albums in tabular format-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 350; top: 350">
<tr bgcolor="#0099FF">
<td colspan="2">
<p align="center"><font color="#000000"><b>  Available Video
Albums</b></font></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#0099FF"><div align="center"><font color="#000000">
<strong>Album Name
</strong></font></div></td>
<td width="147" bgcolor="#0099FF"><div align="center"><font
color="#000000"><b>Company Name </b></font></div></td>
</tr>
<%
/*Create object of DocumentBuilderFactory, using newInstance() method of DocumentBuilderFactory*/
docbfact = DocumentBuilderFactory.newInstance();
/*Create object of DocumentBuilder using the newDocumentBuilder() method of
DocumentBuilderFactory*/
docb = docbfact.newDocumentBuilder();
/*Parse the XML document, musicalbumlist.xml to retrieve the Document object*/
doc = docb.parse(new FileInputStream(videopath));
/*Obtain a NodeList object that represents the elements of the XML file with name album*/
nl1 = doc.getElementsByTagName("album");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object by calling the item() method of NodeList*/
   Node n=nl1.item(int_1);
   /*Obtain the NamedNodeMap object that represents the attributes of the album element*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <tr>
   <!--Retrieve the name attribute value of the album element of the XML file, and display it -->
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("name")).getNodeValue()%></div></td>
   <%
   /*Obtain the NodeLIst object for the sub element company of album element*/
   NodeList nl2 = n.getChildNodes();
   /*Obtain the attributes for the sub element as NamedNodeMap object*/
   Node n2=nl2.item(1);
   NamedNodeMap nnp1 = n2.getAttributes();
   %>
   <!--Retrieve the name attribute value of the company sub element of the XML file, and display it -->
   <td width="147" bgcolor="#FFFFFF"><div
  align="center"><%=(nnp1.getNamedItem("name")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
</div></html>
End example

Download this listing.

The above code creates the Purchase Album page of the online music store application. The code displays fields in which an end user can specify the name of the album to be purchased. Information about music and video albums stored in the musicalbumlist.xml and videoalbumlist.xml files is displayed in tabular format. The code uses DOM to parse both the XML files and retrieve their contents to display album information. When an end user specifies an album name and clicks the Purchase Album button, the code checks whether it is a music or a video album and parses the corresponding musicpurchaselist.xml or videopurchaselist.xml file. After parsing the XML document, the code creates an object tree and adds a node to the tree that corresponds to the album name the end user purchases. Finally, the code uses a Transformer object to transform the object tree to the XML file.

Figure 2-12 shows the Purchase Album page of the online music store application:

Click To expand: This figure shows the Purchase Album page of the online music store application that displays various fields and a Purchase Album button.
Figure 2-12: Purchase Album Page


Creating the Property File

The online music store application uses a property file that stores the path to the XML files of the application. The following code shows the path.properties property file of the application:

userlistpath=c:/Chp2/code/xml/userlist.xml
musicalbumlistpath=c:/Chp2/code /xml/musicalbumlist.xml
videoalbumlistpath=c:/Chp2/code /xml/videoalbumlist.xml
musicpurchaselistpath=c:/Chp2/code /xml/musicpurchaselist.xml
videopurchaselistpath=c:/Chp2/code /xml/videopurchaselist.xml

The above code contains the following properties:

  • userlistpath: Specifies the path to the userlist.xml file.

  • musicalbumlistpath: Specifies the path to the musicalbumlist.xml file.

  • videoalbumlistpath: Specifies the path to the videoalbumlist.xml file.

  • musicpurchaselistpath: Specifies the path to the musicpurchaselist.xml file.

  • videopurchaselistpath: Specifies the path to the videopurchaselist.xml file.

Note

You need to change the values of the above properties in the path.properties file to the directory that stores the XML files of the application.


Unit Testing

You need to deploy and test the online music store application on the Sun Java System Application Server Platform Edition 8. You can download this application server from:

http://java.sun.com/j2ee/1.4/download.html

Note

To install Sun Java System Application Server Platform Edition 8, you need to install Java 2 Standard Edition (J2SE) 1.4.2 on the computer.

To deploy the online music store application:

  1. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Start Default Server from the Start menu to start the application server.

  2. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Deploytool from the Start menu to open the Deployment Tool window.

  3. Select New->Application from the File menu of the Deployment Tool window. The New Application dialog box appears.

  4. Click Browse in the New Application dialog box to display another New Application dialog box.

  5. Select the directory where you want to save the .ear file in the Look In combo box.

  6. Enter the name of the .ear file as OnlineMusicStoreAppl in the File Name text box, as shown in Figure 2-13:

    Click To expand: This figure shows the New Application dialog box in which you can specify the name of the application file and the location to store it.
    Figure 2-13: New Application Dialog Box

  7. Click the New Application button to return to the previous New Application dialog box.

  8. Click OK to create the new application.

  9. Select New->Web Component from the File menu of the Deployment Tool window. The New Web Application Wizard-Introduction dialog box appears.

  10. Click Next. The New Web Application Wizard-Web Archive (WAR) File dialog box appears.

  11. Click Edit Contents in the New Web Application Wizard-WAR File dialog box. The Edit Contents of WebApp dialog box appears.

  12. Select all the JSP files and the path.properties file of the application from the Available Files pane and click Add. The Contents of WebApp pane of the Edit Contents of WebApp dialog box displays the added files, as shown in Figure 2-14:

    Click To expand: This figure shows the Edit Contents of WebApp dialog box that displays the files of the online music store application.
    Figure 2-14: Edit Contents of WebApp Dialog Box

  13. Click OK to add the files to the Web application WAR file.

  14. Click Next in the New Web Application Wizard-WAR File dialog box. The New Web Application Wizard-Choose Component Type dialog box appears.

  15. Select the JSP Page radio button and click Next. The New Web Application Wizard-Component General Properties dialog box appears.

  16. Select Logon.jsp from the JSP Filename drop-down list. The remaining fields get automatically populated with values. Figure 2-15 shows the New Web Application Wizard-Component General Properties dialog box:

    Click To expand: This figure shows the New Web Application Wizard-Component General Properties dialog box in which you specify the main page of your application.
    Figure 2-15: New Web Application Wizardt General Properties Dialog Box

  17. Click Finish.

  18. In the Deployment Tool window, specify/second as the context root of your application in the Context Root text field, as shown in Figure 2-16:

    Click To expand: This figure shows the Context Root text field of the Deployment Tool window in which you can specify the context root of your application.
    Figure 2-16: Deployment Tool Window

  19. Select Save from the File menu of the Deployment Tool window to save the application.

  20. Select Deploy from the Tools menu. The Deploy Module OnlineMusicStoreApp dialog box appears.

  21. Specify the application server user name and password in the User Name and Password fields and click OK.

  22. The Distribute Module dialog box appears. It indicates the successful deployment of the application.

To test the deployed application:

  1. Type the following URL in the address bar of the browser:

    http://localhost:8080/second/Logon.jsp

  2. The logon page of the application appears. Specify admin in the User ID and Password fields, as shown in Figure 2-17:

    Click To expand: This figure shows the logon page of the application that provides the User ID and Password fields to accept end user name and password.
    Figure 2-17: Specifying Logon Information

  3. Click the Submit button. The DoLogon JSP page displays the link to the administrator page.

  4. Select the Go to main page hyperlink. The Administrator Options page appears, as shown in Figure 2-18:

    Click To expand: This figure shows the Administrator Options page that displays various hyperlinks.
    Figure 2-18: Administrator Options Page Containing Hyperlinks

  5. Select the Add user hyperlink. The Add user page appears.

  6. Specify information to add a new end user, as shown in Figure 2-19:

    Click To expand: This figure shows the Add User page that contains fields in which an administrator can specify information about an end user.
    Figure 2-19: Add User Page

  7. Click the Add User button. The List of Existing Users table displays information about the new user, as shown in Figure 2-20:

    Click To expand: This figure shows the List of Existing Users table of the Add New User page. The table displays information about the new user.
    Figure 2-20: List of Existing Users Table

  8. Add a user with administrator role. Check the userlist.xml file to ensure that the information is added to the XML file.

  9. From the Administrator Options page, select the Delete user hyperlink. The Delete User page appears. From the User Name drop-down list, select a user name whose information you want to delete, as shown in Figure 2-21:

    Click To expand: This figure shows the Delete User page in which you can select a user name from the User Name drop-down list to delete its information.
    Figure 2-21: Selecting a User Name

  10. Click Delete User to delete the information. Check the userlist.xml file to ensure that the information is removed.

  11. From the Administrator Options page, select the Add music album hyperlink. The Add Music Album page appears.

  12. Specify information about an album you want to add, as shown in Figure 2-22:

    Click To expand: This figure shows the Add Music Album page that displays the text fields in which you can specify information about a music album you want to add.
    Figure 2-22: Specifying Album Information

  13. Click the Add Music Album button. The Existing Albums table displays information about the music album you added, as shown in Figure 2-23:

    Click To expand: This figure shows the Existing Albums table of the Add Music Album page that displays information about the music album you added.
    Figure 2-23: Existing Albums Table

  14. Check the musicalbumlist.xml file to ensure that the file is updated with the new album information.

  15. Select the Delete music album hyperlink in the Administrator Options page. The Delete Music Album page appears.

  16. From the Music Album Name drop-down list, select an album name whose information you need to delete, as shown in Figure 2-24:

    Click To expand: This figure shows the Delete Music Album page that displays the Music Album Name drop-down list. You can select an album name from this list and delete it.
    Figure 2-24: Deleting a Music Album

  17. Click the Delete Album button to delete information about the selected album.

  18. Select the Add video album and Delete video album hyperlinks in the Administrator Options page to add and delete information about video albums.

  19. Select the Logout hyperlink to return to the Logon page.

  20. In the Logon page, specify the name and password of the end user with user role you created using steps 5 through 7.

  21. Click the Submit button. The DoLogon JSP page displays the user interface for the user role, as shown in Figure 2-25:

    Click To expand: This figure shows the user interface that appears when an end user with user role logs on to the application.
    Figure 2-25: User Interface of the DoLogon JSP Page

  22. Select the Go to main page hyperlink. The Purchase Album page appears.

  23. To purchase a music album, select MUSIC from the Select Album drop-down list and specify the album name in the text field, as shown in Figure 2-26:

    Click To expand: This figure shows the Purchase Album page that displays the Select Album drop-down list and a text field in which you can specify the album name you want to purchase.
    Figure 2-26: Specifying the Album Name

  24. Click the Purchase Album button to submit the information.

  25. Select the Go to main page hyperlink. The DoLogon page displays the album you purchased, as shown in Figure 2-27:

    Click To expand: This figure shows the DoLogon page that displays information about the albums you purchased.
    Figure 2-27: DoLogon Page Displaying Purchased Album

  26. Select the Logout hyperlink to logout from the online music store application.


Point 3: Creating a JSPXML Integrated System Using JDOM

Java Document Object Model (JDOM) is an open source API developed under the Apache license that allows Java applications to read and write data to XML files. You can use JDOM in a JSP application to work with XML documents that store application data. You can also use JDOM in JSP applications as an alternative to the Document Object Model (DOM) and Simple API for XML (SAX). This is because JDOM offers a simple abstraction of SAX and DOM to provide access to an XML document from a Java application. JDOM creates an object tree of an XML document in the memory. You can code JSP pages to create instances of JDOM classes to work with the nodes of the object tree. You can then code JSP pages to transform the object tree back to the XML document.

This chapter describes how to develop an online directory application using JSP. The application data is stored in XML files. The JSP pages of the application use JDOM to parse, create, manipulate, and transform the XML documents.

Requirements of the Online Directory Application

The online directory application enables registered end-users to log on and search the names of organizations by specifying criteria, such as category, city, or zip code. New users can register to access the application data. The application administrator can add and delete data about new and existing organizations.

The online directory application stores application data in the following XML files:

  • userlist.xml: Stores registration information of end-users.

  • directorylist.xml: Stores information of organizations as directory entries.

The online directory application can be divided into the following four modules:

  • Logon module: Provides user authentication. The files of the logon module are:

    • Logon.jsp: Provides the User Logon page that displays the fields to accept end-user logon information.

    • DoLogon.jsp: Authenticates end-user logon information, such as user ID and password, using data stored in the userlist.xml file.

  • Registration module: Allows new users to register with the application. The files of the registration module are:

    • UserRegistration.jsp: Provides the User Registration page that displays the fields to accept end-user registration information.

    • RegisterUser.jsp: Stores end-user registration information in the userlist.xml file.

  • Administrator module: Allows the administrator to add and delete entries. The files of the administrator module are:

    • AdminPage.jsp: Displays links to the other user interfaces of the administrator module.

    • AddEntry.jsp: Displays the fields in which the administrator can specify information to add a new entry.

    • DoAddEntry.jsp: Stores new entries to the directorylist.xml file.

    • DeleteEntry.jsp: Displays the fields in which the administrator can specify information to delete an entry.

    • DoDeleteEntry.jsp: Removes an entry from the directorylisting.xml file.

  • User module: Allows end-users to search for organizations by specifying criteria, such as category, city, or zip code. The files of the user module are:

    • UserPage.jsp: Displays links to the other user interfaces of the user module.

    • Category.jsp: Allows end-users to search for organizations using the category criterion.

    • City.jsp: Allows end-users to search for organizations using the city criterion.

    • Zip.jsp: Allows end-users to search for organizations using the zip code criterion.

Figure 3-1 shows the architecture of the online directory application:

Click To expand: This figure shows the JSP files of the online directory application and the sequence in which the files are used.
Figure 3-1: Architecture of the Online Directory Application


Creating the XML Files

The userlist.xml file stores end-user registration data, such as user ID, password, address, and role, as shown in Listing 3-1:

Listing 3-1: The userlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<userlist>
<user city="Oakland" country="United States" email="admin@yellowpages.com" firstname="Albert"
lastname="Johnson" name="admin" password="admin">
<role name="administrator" />
</user>
<user city="Oakland" country="United States" email="peter@yellowpages.com" firstname="Peter"
lastname="Smith" name="Peter" password="peter">
<role name="user" />
</user>
</userlist>
End example

Download this listing.

The above code uses the userlist root element that contains user elements. A user element contains the city, country, email, firstname, lastname, name, and password attributes. Each user element contains a role element. The name attribute of the role element represents an end-user role.

The directorylist.xml file stores information about directory entries, such as entry ID, category, organization name, address, and phone number. Listing 3-2 shows the content of the directorylist.xml file:

Listing 3-2: The directorylist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<yellowpage>
<entry category="Real Estate" id="172-32-1176" organization="Sync View Estates
Inc"><contact address="3410 Blonde St." city="Palo Alto" phone="408 496-7223" zip="94301"
/>
</entry>
<entry category="Real Estate" id="893-72-1158" organization="Stub Buyers Inc.">
<contact address="5420 Telegraph Av." city="Oakland" phone="415 935-4228" zip="94612"/>
</entry>
</yellowpage>
End example

Download this listing.

The above code contains the yellowpage root element that encloses entry elements. Each entry element represents a directory entry and contains the category, id, and organization attributes. Each entry element encloses a contact element that contains the address, city, phone number, and zip code attributes.


Creating the Logon Module

The logon module of the online directory application provides the User Logon Page that accepts end-user logon information. The logon module also provides a logon handler that verifies the end-user logon information by comparing it with the data stored in the userlist.xml file. The logon module contains the Logon.jsp and DoLogon.jsp files.

Creating the User Logon Page

The Logon.jsp file creates the User Logon page to accept user ID and Password of end-users.

Listing 3-3 shows the content of the Logon.jsp file:

Listing 3-3: The Logon.jsp File
Start example
<html>
<head>
<title>Online Directory</title>
</head>
<body bgcolor="#CCFFCC">
<div align="center">
<table width="93%" height="79" border="1">
<tr>
<td width="100%" height="55" align="center" bgcolor="#C0C0C0">
<p align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
Directory</font></b></td>
</tr>
</table>
</div>
<div align="center">
<form name="form1" method="Post" action="DoLogon.jsp">
<table border="1" width="71%" bgcolor="#CCCCCC">
<tr>
<td width="50%" colspan = 2>
<div align="center"><font color="#990000"><b> User
Logon</b></font></div>
</td>
</tr>
<tr>
<td width="50%">
<div align="center"><font color="#990000"><strong>User
ID:</strong></font></div></td>
<td width="50%"><font color="#990000">
<input type="text" name="textfieldUserID" size="50">
</font></td>
</tr>
<tr>
<td width="50%">
<div align="center"><font
color="#990000"><strong>Password:</strong></font></div></td>
<td width="50%"><font color="#990000">
<input type="password" name="textfieldPassword" size="50">
</font></td>
</tr>
<tr>
<td width="50%" height="27">
<div align="right"> <font color="#990000">
<input type="submit" name="Submit" value="Logon">
</font></div>
</td>
<td width="50%" height="27"><font color="#990000">
<input type="RESET" name="Refresh" value="Refresh">
</font></td>
</tr>
</table>
</form>
<a href="UserRegistration.jsp">New user </a></div>
</body>
</html>
End example

Download this listing.

The above code creates the User Logon page that contains the User ID and Password text fields. This page also contains a Submit button and a New user hyperlink. The end-user needs to specify the logon data and click Submit to submit the data to the DoLogon JSP page.

Figure 3-2 shows the User Logon page of the online directory application:

Click To expand: This figure shows the User Logon page that displays the User ID and Password fields. This page also contains a New user hyperlink.
Figure 3-2: The User Logon Page

Creating the Logon Handler

The logon handler uses JDOM to parse the userlist.xml file and compares the end-user specification with the data stored in the XML document. The DoLogon JSP page is the logon handler of the application. Listing 3-4 shows the content of the DoLogon.jsp file:

Listing 3-4: The DoLogon.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%! String userpath;%>
<%
boolean logonstatus = false;
String role="";
String username,password;
/*Retrieve user ID and Password using request object*/
username=request.getParameter("textfieldUserID");
password=request.getParameter("textfieldPassword");
/*Check whether both user ID and Password are specified*/
if(!(username==null || password==null))
{
try
     {
         /*Create a URL object to load the properties file*/
         URL url=new URL("http://127.0.0.1:8080/third/path.properties");
         /*Open URL connection*/
         URLConnection ucon=url.openConnection();
         /*Retrieve the userlistpath property*/
         Properties prop = new Properties();
         prop.load(ucon.getInputStream());
         userpath = prop.getProperty("userlistpath");
      }
      catch(Exception ex)
      {
         ex.printStackTrace();
      }
      /*Obtain a JAXPDOMAdapter object*/
      org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new
      org.jdom.adapters.JAXPDOMAdapter();
      /*Call he getDocument() method to parse the userlist.xml file and obtain a Document object*/
      org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new
      FileInputStream(userpath), false);
      /*Create a new DOMBuilder object*/
      org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
      /*Call the build() method to obtain a JDOM Document*/
      org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
      /*Call the getRootElement method to retrieve the root element of the XML document*/
      org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
      /*Retrieve all child elements of the root element as a List object*/
      java.util.List UserList = RootElement.getChildren();
      /*Iterate through the List object*/
      for(int cntr1 = 0; cntr1<UserList.size(); cntr1 ++)
      {
         /*Retrieve a child element, tempElement of root element*/
         org.jdom.Element tempElement = (org.jdom.Element)(UserList.get(cntr1));
         /*Retrieve name and password attributes*/
         String tempuser = tempElement.getAttributeValue("name");
         String temppasswd = tempElement.getAttributeValue("password");
         /*Check if retrieved values matches with end-user values*/
         if(username.equals(tempuser)&& password.equals(temppasswd))
            {
               /*If logon information matches, set logonstatus boolean value to true*/
               logonstatus = true;
               /*Obtain the role sub element*/
               org.jdom.Element ElementRole = tempElement.getChild("role");
               /*Retrieve name attribute of the role element*/
               role = ElementRole.getAttributeValue("name");
               /*Store user ID and role in session*/
               session.setAttribute("username",username);
               session.setAttribute("role", role);
            }
      }
}
else
{
   /*If authentication fails, forward request to Logon.jsp*/
   %>
   <jsp:forward page="Logon.jsp"/>
   <%
}
%>
<!--Page design-->
<html>
<head>
<title>Online Directory</title>
</head>
<body bgcolor="#CCFFCC">
<div align="center">
<table width="93%" height="79" border="1">
<tr>
<td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
Directory</font></b></td>
</tr>
</table>
<div align="center">
<% if(logonstatus==true)
  {
   %>
   <!--For successful authentication, display welcome message-->
   <p><font size="+1" color="#800000">Hello <%=username%>! Welcome to Online
   Directory.</font></p>
   <%
  }
  else
  {
     %>
      <!--For unsuccessful authentication, display error message-->
      <p><font size="+1" color="#800000">Invalid logon information . Please log on again.
      </font></p>
      <p><a href="Logon.jsp">Back to logon page </a></p>
      <%
  }
%>
</div>
</div>
<div align="center">
<%
if("user".equals(role))
{
   %>
   <!--For user role, display hyperlink to UserPage.jsp-->
   <p><a href="UserPage.jsp">Go to main page</a></p>
   <%
}
else if("administrator".equals(role))
{
   %>
   <!--For administrator role, display hyperlink to AdminPage.jsp-->
   <p><a href="AdminPage.jsp">Go to admin page</a></p>
   <%
}
%>
</div>
<div align="center"> </div>
</body>
</html>
End example

Download this listing.

The above code creates the DoLogon JSP page. The code uses the getParameter() method of the request object to obtain the user ID and password values. A JAXPDOMAdapter object is used in the code to call the getDocument() method. The getDocument() method returns a Document object of the userlist XML document. The build() method of the code converts the Document object into a JDOM document. The code retrieves the root element of the XML document using the getRootElement() method. To compare logon information stored as attributes in the child elements, the code iterates through the child elements of the root element. For the child element whose attribute values match those specified by the end-user, the code retrieves the role subelement. The code obtains the role value and stores it along with the user ID value in the session object. For a user role, the code displays the Go to user page hyperlink. The code displays the Go to admin page hyperlink for an administrator role.

Figure 3-3 shows the user interface provided by the DoLogon JSP page after authenticating an end-user with administrator role:

Click To expand: This figure shows the user interface that displays the Go to admin page hyperlink.
Figure 3-3: User Interface of the DoLogon JSP Page for Administrator Role

Figure 3-4 shows the user interface provided by the DoLogon JSP page after authenticating an end-user with user role:

Click To expand: This figure shows the user interface that displays the Go to user page hyperlink.
Figure 3-4: User Interface of the DoLogon JSP Page for User Role


Creating the Registration Module

The registration module uses the UserRegistration.jsp and RegisterUser.jsp files to display the User Registration page and record registration information in the userlist.xml file.

Creating the User Registration Page

The UserRegistration.jsp file creates the User Registration page to accept registration data of end-users.

Listing 3-5 shows the content of the UserRegistration.jsp file:

Listing 3-5: The UserRegistration.jsp File
Start example
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
if(username==null || role==null||"administrator".equals(role))
{
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <h3>User Registration</h3>
   <table width="200" border="0">
   <!--Return to Logon.jsp page-->
   <tr>
   <td><div align="center"><a href="Logon.jsp">Return to User Logon page
   </a></div></td>
   <td><div align="right"></div>
   <div align="right"></div></td>
   </tr>
   </table>
   </div>
   <div align="right"></div>
   <div align="center">
   <!--Display User Details form and submit data to RegisterUser.jsp-->
   <form name="form1" method="post" action="RegisterUser.jsp">
   <table border="1" width="71%" bgcolor="#CCCCCC">
   <tr>
   <td width="50%" colspan = 2>
   <div align="center"><font color="#990000"><b>User
   Details</b></font></div>
   </td>
   </tr>
   <tr>
   <!--Display User ID text field-->
   <td width="50%">
   <div align="center"><font color="#990000"><strong>User
   ID:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldUserID" size="50">
   </font></td>
   </tr>
   <!--Display Password password field-->
   <tr>
   <td width="50%">
   <div align="center"><font
   color="#990000"><strong>Password</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="password" name="textfieldPassword" size="50">
   </font></td>
   </tr>
   <!--Display First Name text field-->
   <tr>
   <td width="50%">
   <div align="center"><font color="#990000"><strong>First
   Name:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldFirstName" size="50">
   </font></td>
   </tr>
   <!--Display Last Name text field-->
   <tr>
   <td width="50%">
   <div align="center"><font color="#990000"><strong>Last
   Name:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldLastName" size="50">
   </font></td>
   </tr>
   <!--Display Address text field-->
   <tr>
   <td width="50%" height="18">
   <div align="center"><font
   color="#990000"><strong>Address:</strong></font></div></td>
   <td width="50%" height="18"><font color="#990000">
   <input type="text" name="textfieldAddress" size="50">
   </font></td>
   </tr>
   <!--Display City text field-->
   <tr>
   <td width="50%">
   <div align="center"><font
   color="#990000"><strong>City:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldCity" size="50">
   </font></td>
   </tr>
   <!--Display Country text field-->
   <tr>
   <td width="50%">
   <div align="center"><font
   color="#990000"><strong>Country:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldCountry" size="50">
   </font></td>
   </tr>
   <!--Display Email Address: text field-->
   <tr>
   <td width="50%">
   <div align="center"><font color="#990000"><strong>Email
   Address:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldEmail" size="50">
   </font></td>
   </tr>
   <!--Display Submit and Reset button-->
   <tr>
   <td width="50%" height="27">
   <div align="right"> <font color="#990000">
   <input type="submit" name="Submit" value="Submit">
   </font></div>
   </td>
   <td width="50%" height="27"><font color="#990000">
   <input type="RESET" name="Submit2" value="Cancel">
   </font></td>
   </tr>
   </table>
   </form>
   </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the User Registration page. This code displays the fields to accept end-user registration information and provides a Submit button to submit the information to the RegisterUser.jsp file.

Figure 3-5 shows the User Registration page of the online directory application:

Click To expand: This figure shows the User Registration page that displays the User ID, Password, First Name, Last Name, Address, City, Country, and Email Address fields.
Figure 3-5: The User Registration Page

Creating the RegisterUser JSP Page

The RegisterUser JSP page uses JDOM to insert registration information about new end-users into the userlist.xml file. After registration, the RegisterUser JSP page displays a successful registration message.

Listing 3-6 shows the content of the RegisterUser.jsp file:

Listing 3-6: The RegisterUser.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String userpath;%>
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
if(username==null || role==null || "administrator".equals(role))
{
   String userid,password,firstname,lastname,address,city,country,email;
   /*Use request object to retrieve user registration data*/
   userid=request.getParameter("textfieldUserID");
   password=request.getParameter("textfieldPassword");
   firstname=request.getParameter("textfieldFirstName");
   lastname=request.getParameter("textfieldLastName");
   address=request.getParameter("textfieldAddress");
   city=request.getParameter("textfieldCity");
   country=request.getParameter("textfieldCountry");
   email=request.getParameter("textfieldEmail");
   try
   {
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/third/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the userlistpath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      userpath = prop.getProperty("userlistpath");
   }
   catch(Exception ex)
   {
   ex.printStackTrace();
   }
   /*Obtain a JAXPDOMAdapter object*/
   org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
   /*Call he getDocument() method to parse the userlist.xml file and obtain a Document object*/
   org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new
   FileInputStream(userpath), false);
   /*Create a new DOMBuilder object*/
   org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
   /*Call the build() method to obtain a JDOM Document*/
   org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
   /*Call the getRootElement method to retrieve the root element of the XML document*/
   org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
   /*Retrieve all child elements of the root element as a List object*/
   java.util.List UserList = RootElement.getChildren();
   /*Create a new user element*/
   org.jdom.Element userelement = new org.jdom.Element("user");
   /*Set name attribute of user element*/
   userelement.setAttribute("name",userid);
   /*Set password attribute of user element*/
   userelement.setAttribute("password",password);
   /*Set firstname attribute of user element*/
   userelement.setAttribute("firstname",firstname);
   /*Set lastname attribute of user element*/
   userelement.setAttribute("lastname",lastname);
   /*Set city attribute of user element*/
   userelement.setAttribute("city",city);
   /*Set country attribute of user element*/
   userelement.setAttribute("country",country);
   /*Set email attribute of user element*/
   userelement.setAttribute("email",email);
   /*Create a new role element*/
   org.jdom.Element roleelement = new org.jdom.Element("role");
   /*Set name attribute of role element*/
   roleelement.setAttribute("name","user");
   /*Add role element to user element*/
   userelement.addContent(roleelement);
   /*Add user element to root element*/
   RootElement.addContent(userelement);
   /*Obtain a XMLOutputter object*/
   org.jdom.output.XMLOutputter xmlout = new org.jdom.output.XMLOutputter();
   /*Write the updated JDOM Document to the XML document*/
   xmlout.output(JDOMDocument_1,new java.io.FileOutputStream(userpath));
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <!--Display message to indicate that registration has been successfuly done-->
   <p><font size="+1" color="#800000">You have been successfuly
   registered.</font></p>
   <p>&nbsp;</p>
   </div>
   <!--Display hyperlinks to Logon.jsp-->
   <div align="center"><a href="Logon.jsp">Go to Logon page</a></div>
   <div align="center"></div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the RegisterUser JSP page. This code uses the request object to obtain end-user specified registration information. The code creates a JDOM Document object from the userlist XML document and obtains the root element using the getRootElement() method of the Document object. Next, the code creates a new Element object that corresponds to the user element of the userlist XML document. The code sets the attribute that represents registration information to the Element object using the setAttribute() method of the Element object. Next, the code creates another Element object that corresponds to the role element of the userlist XML document. The code then adds the name attribute to the Element object. The code appends the role element to the user element, which in turn is appended to the root element. Finally, the code uses the output() method of the XMLOutputter object to transform the JDOM document back to the XML document. After transformation, the code displays a success message.


Creating the Administrator Module

The administrator module of the online directory application allows an end-user with administrator role to add and delete organization information that is stored as a directory entry. The administrator module contains the AdminPage.jsp, AddEntry.jsp, and DeleteEntry.jsp files that provide the Administrator Options, Add Entry, and Delete Entry pages. The DoAddEntry.jsp and DoDeleteEntry.jsp files of the administrator module access the directorylist.xml file to add and delete directory entries.

Creating the Administrator Options Page

The AdminPage.jsp file creates the Administrator Options page.

Listing 3-7 shows the content of the AdminPage.jsp file:

Listing 3-7: The AdminPage.jsp File
Start example
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("administrator".equals(role))
{
   /*For administrator role*/
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <!--Display hyperlinks to Logon.jsp a-->
   <p><a href="Logon.jsp">Logout</a></p>
   <p>&nbsp;</p>
   </div>
   <div align="center">
   <!--Create Administrator Options table-->
   <table border="1" width="46%" bgcolor="#CCCCCC">
   <tr>
   <td width="50%"><div align="center"><font
   color="#990000"><b>Administrator Options
   </b></font></div></td>
   </tr>
   <tr>
   <!--Display hyperlinks to AddEntry.jsp and AdminPage.jsp-->
   <tr>
   <td width="50%"><div align="center"><a href="AddEntry.jsp">Add
   entry</a></div>
   <tr>
   <!--Display hyperlinks to DeleteEntry.jsp-->
   <td width="50%"><div align="center"><a href="DeleteEntry.jsp">Delete
   entry</a></div></td>
   </tr>
   </table>
   </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the Administrator Options page of the online directory application. The code retrieves the user ID and role values of an end-user, which are stored in the session object. If the session object does not contain the user ID or role value, the code redirects the request to the User Logon page. For an end-user with administrator role, the code displays the hyperlinks to the AddEntry.jsp and DeleteEntry.jsp files.

Figure 3-6 shows the Administrator Options page of the online directory application:

Click To expand: This figure shows the Administrator Options page that displays the Add and Delete entry hyperlinks.
Figure 3-6: The Administrator Options Page

Creating the Add Entry Page

The Add Entry page of the online directory application displays the fields in which the administrator can specify information about an organization to add it as a directory entry. The Add Entry page contains the Add button that submits the specified information to the DoAddEntry JSP. The AddEntry.jsp file provides the Add Entry page of the online directory application.

Listing 3-8 shows the content of the AddEntry.jsp file:

Listing 3-8: The AddEntry.jsp File
Start example
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("administrator".equals(role))
{
   /*For administrator role*/
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <h3><strong>Add Entry</strong></h3>
   <!--Display hyperlinks to Logon.jsp and AdminPage.jsp -->
   <table width="372" border="0">
   <tr>
   <td width="132"><div align="center"><a href="Logon.jsp">Logout
   </a></div></td>
   <td width="230"><div align="center"><a href="AdminPage.jsp">Back to main
   page</a></div></td>
   </tr>
   </table>
   </div>
   <!--Create HTML Form to submit data to DoAddEntry.jsp -->
   <div align="center"><form name="form1" method="post" action="DoAddEntry.jsp">
   <table border="1" width="71%" bgcolor="#CCCCCC">
   <tr>
   <td width="50%" colspan = 2>
   <div align="center"><font color="#990000"><b>ENTRY
   DETAILS</b></font></div>
   </td>
   </tr>
   <tr>
   <!--Display Serial No text field -->
   <td width="50%">
   <div align="center"><font color="#990000"><strong>Serial
   No:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldSerialId" size="50" >
   </font></td>
   </tr>
   <!--Display Category text field -->
   <tr>
   <td width="50%">
   <div align="center"><font
 color="#990000"><strong>Category:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldCategory" size="50" >
   </font></td>
   </tr>
   <!--Display Organization text field -->
   <tr>
   <td width="50%">
   <div align="center"><font
 color="#990000"><strong>Organization:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldOrganization" size="50" >
   </font></td>
   </tr>
   <!--Display Address text field -->
   <tr>
   <td width="50%">
   <div align="center"><font
   color="#990000"><strong>Address:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldAddress" size="50" >
   </font></td>
   </tr>
   <!--Display Phone No text field -->
   <tr>
   <td width="50%" height="18">
   <div align="center"><font color="#990000"><strong>Phone
   No:</strong></font></div></td>
   <td width="50%" height="18"><font color="#990000">
   <input type="text" name="textfieldPhone" size="50" >
   </font></td>
   </tr>
   <tr>
   <td width="50%">
   <div align="center"><font
   color="#990000"><strong>City:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldCity" size="50">
   </font></td>
   </tr>
   <tr>
   <td width="50%">
   <div align="center"><font
   color="#990000"><strong>State:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldState" size="50">
   </font></td>
   </tr>
   <!--Display Zip Code text field -->
   <tr>
   <td width="50%">
   <div align="center"><font color="#990000"><strong>Zip
   Code:</strong></font></div></td>
   <td width="50%"><font color="#990000">
   <input type="text" name="textfieldZip" size="50">
   </font></td>
   </tr>
   <!--Add Submit and Reset button -->
   <tr>
   <td width="50%" height="27">
   <div align="right"> <font color="#990000">
   <input type="submit" name="Submit" value="Add">
   </font></div>
   </td>
   <td width="50%" height="27"><font color="#990000">
   <input type="submit" name="Refresh" value="Refresh">
   </font></td>
   </tr>
   </table>
   </form>
   </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the Add Entry page of the online directory application. The code checks for an end-user role stored in the session object. For the administrator role, the code displays the fields in which an end-user can specify information about a new directory entry. The code also displays a Submit button that allows the end-user to submit information about a new entry to the DoAddEntry JSP page.

Figure 3-7 shows the Add Entry page of the online directory application:

Click To expand: This figure shows the Add Entry page that displays the Serial No, Category, Organization, Address, Phone No, City, and Zip Code text fields.
Figure 3-7: The Add Entry Page

Creating the DoAddEntry JSP Page

The DoAddEntry JSP page records information about an organization as a directory entry to the directorylist.xml file. After adding an entry, the DoAddEntry JSP page displays a success message.

Listing 3-9 shows the content of the DoAddEntry.jsp file:

Listing 3-9: The DoAddEntry.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String ypagespath;%>
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("administrator".equals(role))
{
/*If user role is administrator, retrieve values of new entry from request object*/
String serialid,category,organization,email,address,phone,city,state,zip;
serialid=request.getParameter("textfieldSerialId");
organization=request.getParameter("textfieldOrganization");
category=request.getParameter("textfieldCategory");
address=request.getParameter("textfieldAddress");
phone=request.getParameter("textfieldPhone");
city=request.getParameter("textfieldCity");
state=request.getParameter("textfieldState");
zip=request.getParameter("textfieldZip");
try{
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/third/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the directorypath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      ypagespath = prop.getProperty("directorypath");
   }
catch(Exception ex)
{
   ex.printStackTrace();
}
/*Obtain a JAXPDOMAdapter object*/
org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
/*Call he getDocument() method to parse the directorylist.xml file and obtain a Document object*/
org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new FileInputStream(ypagespath),false);
/*Create a new DOMBuilder object*/
org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
/*Call the build() method to obtain a JDOM Document*/
org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
/*Call the getRootElement method to retrieve the root element of the XML document*/
org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
/*Retrieve all child elements of the root element as a List object*/
java.util.List EntryList = RootElement.getChildren();
/*Create a entry element*/
org.jdom.Element entryelement = new org.jdom.Element("entry");
/*Set id attribute of entry element*/
entryelement.setAttribute("id",serialid);
/*Set id category attribute of entry element*/
entryelement.setAttribute("category",category);
/*Set organization attribute of entry element*/
entryelement.setAttribute("organization",organization);
/*Create a contact element*/
org.jdom.Element contactelement = new org.jdom.Element("contact");
/*Set address attribute of contact element*/
contactelement.setAttribute("address",address);
/*Set phone attribute of contact element*/
contactelement.setAttribute("phone",phone);
/*Set city attribute of contact element*/
contactelement.setAttribute("city",city);
/*Set state attribute of contact element*/
contactelement.setAttribute("state",state);
/*Set zip attribute of contact element*/
contactelement.setAttribute("zip",zip);
/*Add contact element to entry element*/
entryelement.addContent(contactelement);
/*Add entry element to root element*/
RootElement.addContent(entryelement);
/*Obtain a XMLOutputter object*/
org.jdom.output.XMLOutputter xmlout = new org.jdom.output.XMLOutputter();
/*Write the updated JDOM Document to the XML document*/
xmlout.output(JDOMDocument_1,new java.io.FileOutputStream(ypagespath));
%>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Online Directory</title>
</head>
<body bgcolor="#CCFFCC">
<div align="center">
<table width="93%" height="79" border="1">
<tr>
<td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
Directory</font></b></td>
</tr>
</table>
<!--Display message to indicate that entry has been successfuly added-->
<p><strong>Entry successfuly added. </strong></p>
<table width="381" border="0">
<tr>
<!--Display hyperlinks to AdminPage.jsp and AddEntry.jsp-->
<td width="194"><a href="AdminPage.jsp">Back to main page</a></td>
<td width="177"><a href="AddEntry.jsp">Add more entry</a></td>
</tr>
</table>
<p><strong></strong></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>
<div align="center"><p><a href="Logon.jsp"> </a></p>
</div>
<div align="center"> </div>
</body>
</html>
<%
}
%>
End example

Download this listing.

The above code creates the DoAddEntry JSP page. The code uses the request object to obtain information about a new entry. The getDocument() method parses the directorylist.xml file and creates a JDOM Document object of the file. To add directory entries, the code creates a new Element object that corresponds to the entry element of the XML document. The setAttribute() methods of the Element object sets the id, category, and organization attributes. The code creates another Element object that corresponds to the contact element of the XML document. The setAttribute() methods add the address, phone number, city, and zip code attributes to the contact element. The addContent() method adds the contact element to the entry element and the entry element to the root element. Finally the code calls the output() method of the XMLOutputter object to transform the JDOM Document to the directorylist XML document.

Creating the Delete Entry Page

The Delete Entry page of the online directory application allows an end-user with administrator role to delete entries. The Delete Entry page displays entries with corresponding Delete buttons. The DeleteEntry.jsp file provides the Delete Entry page of the online directory application.

Listing 3-10 shows the content of the DeleteEntry.jsp file:

Listing 3-10: The DeleteEntry.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String ypagespath;%>
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("administrator".equals(role))
{
   /*For administrator role, proceed*/
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <p><strong>Delete Entry</strong></p>
   <table width="372" border="0">
   <tr>
   <!--Display hyperlinks to Logon.jsp and AdminPage.jsp -->
   <td width="132"><div align="center"><a href="Logon.jsp">Logout
   </a></div></td>
   <td width="230"><div align="center"><a href="AdminPage.jsp">Back to main
   page</a></div></td>
   </tr>
   </table>
   <p>&nbsp;</p>
   </div>
   <div align="right"></div>
   <div align="center">
   <!--Display table headings -->
   <table border="1" width="92%" bgcolor="#CCCCCC">
   <tr>
   <td width="4%">
   <div align="center"><b><font color="#990000">Serial
   No</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">Category</font></b></div>
   </td>
   <td width="15%">
   <div align="center"><b><font
   color="#990000">Organization</font></b></div>
   </td>
   <td width="13%">
   <div align="center"><b><font
   color="#990000">Address</font></b></div>
   </td>
   <td width="13%">
   <div align="center"><b><font
   color="#990000">Phone</font></b></div>
   </td>
   <td width="13%">
   <div align="center"><b><font
   color="#990000">City</font></b></div>
   </td>
   <td width="13%">
   <div align="center"><b><font
   color="#990000">Zip</font></b></div>
   </td>
   <td width="6%">
   <div align="center"><b> </b></div>
   </td>
   </tr>
   <%
   try{
   /*Create a URL object to load the properties file*/
   URL url=new URL("http://127.0.0.1:8080/third/path.properties");
   /*Open URL connection*/
   URLConnection ucon=url.openConnection();
   /*Retrieve the directorypath property*/
   Properties prop = new Properties();
   prop.load(ucon.getInputStream());
   ypagespath = prop.getProperty("directorypath");
}
catch(Exception ex)
{
   ex.printStackTrace();
}
/*Obtain a JAXPDOMAdapter object*/
org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
/*Call he getDocument() method to parse the directorylist.xml file and obtain a Document object*/
org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new FileInputStream(ypagespath),false);
/*Create a new DOMBuilder object*/
org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
/*Call the build() method to obtain a JDOM Document*/
org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
 /*Call the getRootElement method to retrieve the root element of the XML document*/
org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
/*Retrieve all child elements of the root element as a List object*/
java.util.List UserList = RootElement.getChildren();
/*Iterate through the List object*/
for(int cntr1 = 0; cntr1<UserList.size(); cntr1 ++)
   {
      /*Retrieve a child element, tempElement of root element*/
      org.jdom.Element tempElement = (org.jdom.Element)(UserList.get(cntr1));
      /*Retrieve attributes of the child element*/
      String tempid = tempElement.getAttributeValue("id");
      String tempcategory = tempElement.getAttributeValue("category");
      String temporganization = tempElement.getAttributeValue("organization");
      /*Retrieve child element of tempElement*/
      org.jdom.Element contactElement = tempElement.getChild("contact");
      /*Retrieve attributes of the child element*/
      String tempaddress = contactElement.getAttributeValue("address");
      String tempphone = contactElement.getAttributeValue("phone");
      String tempcity = contactElement.getAttributeValue("city");
      String tempzip = contactElement.getAttributeValue("zip");
      %>
      <tr>
      <!--Display form to and submit to DoDeleteEntry.jsp-->
      <form name="form1" method="post" action="DoDeleteEntry.jsp">
      <td width="4%">
      <!--Include hidden field to track entry-->
      <div align="center"><b> <%=tempid%></b></div>
      <input type="hidden" name="textfieldid" value="<%=tempid%>">
      </td>
      <!--Display directory information with a delete button to delete the information-->
      <td width="10%">
      <div align="center"><b>
      <input type="text" name="textfieldCategory" value="<%=tempcategory%>">
      </b></div>
      </td>
      <td width="15%">
      <div align="center"><b>
      <input type="text" name="textfieldOrganization" value="<%=temporganization%>">
      </b></div>
      </td>
      <td width="13%">
      <div align="center"><b>
      <input type="text" name="textfieldAddress" value="<%=tempaddress%>">
      </b></div>
      </td>
      <td width="13%">
      <div align="center"><b>
      <input type="text" name="textfieldPhone" value="<%=tempphone%>">
      </b></div>
      </td>
      <td width="13%">
      <div align="center"><b>
      <input type="text" name="textfieldCity" value="<%=tempcity%>">
      </b></div>
      </td>
      <td width="13%">
      <div align="center"><b>
      <input type="text" name="textfieldZip" value="<%=tempzip%>">
      </b></div>
      </td>
      <td width="6%">
      <div align="center"><b>
      <input type="submit" name="Delete1" value="Delete">
      </b></div>
      </td>
      </form>
      </tr>
      <%
   }
%>
</table>
</div>
</body>
</html>
<%
}
%>
End example

Download this listing.

The above code creates the Delete Entry page of the online directory application. The code checks for an end-user role stored in the session object. For the administrator role, the code parses the yellowpages XML document using JDOM. The code iterates through the elements of the XML document and displays the contents in tabular format. For each entry, the code displays a Delete button to delete the entry. When the end-user clicks the Delete button, the code submits the information to the DoDeleteEntry JSP page.

Figure 3-8 shows the Delete Entry page of the online directory application:

Click To expand: This figure shows the Delete Entry page that displays information about the entries and their corresponding Delete buttons.
Figure 3-8: The Delete Entry Page

Creating the DoDeleteEntry JSP Page

The DoDeleteEntry JSP page removes a directory entry from the directorylist.xml file. The DoDeleteEntry JSP file obtains the serial number of the entry that is to be removed and uses JDOM to remove the node that corresponds to that serial number. After removing an entry, the code displays a success message.

Listing 3-11 shows the content of the DoDeleteEntry.jsp file:

Listing 3-11: The DoDeleteEntry.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String ypagespath,id;%>
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("administrator".equals(role))
{
   /*If user role is administrator, retrieve id of record to delete from request object*/
   id= request.getParameter("textfieldid");
   if(id==null)
   {
      id="";
   }
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <p><strong>Entry successfuly deleted.</strong></p>
   <p>&nbsp;
   </p>
   <table width="547" border="0">
   <!--Display hyperlinks to Logon.jsp,AdminPage.jsp, and DeleteEntry.jsp-->
   <tr>
   <td width="104"><div align="center"><a
   href="Logon.jsp">Logout</a></div></td>
   <td width="189"><div align="center"><a href="AdminPage.jsp">Back to main
   page</a></div></td>
   <td width="240"><div align="center"><a href="DeleteEntry.jsp">Delete more
   entries</a></div></td>
   </tr>
   </table>
   <p>&nbsp;</p>
   </div>
   <div align="right"></div>
   <div align="right"></div>
   <div align="center">
   <%
   try
   {
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/third/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the directorypath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      ypagespath = prop.getProperty("directorypath");
   }
   catch(Exception ex)
   {
      ex.printStackTrace();
   }
   /*Obtain a JAXPDOMAdapter object*/
   org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
   /*Call he getDocument() method to parse the directorylist.xml file and obtain a Document
   object*/
   org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new
   FileInputStream(ypagespath),false);
   /*Create a new DOMBuilder object*/
   org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
   /*Call the build() method to obtain a JDOM Document*/
   org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
   /*Call the getRootElement method to retrieve the root element of the XML document*/
   org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
   /*Retrieve all child elements of the root element as a List object*/
   java.util.List UserList = RootElement.getChildren();
   /*Iterate through the List object*/
   for(int cntr1 = 0; cntr1<UserList.size(); cntr1 ++)
   {
      /*Retrieve a child element, tempElement of root element*/
      org.jdom.Element tempElement = (org.jdom.Element)(UserList.get(cntr1));
      /*Retrieve attributes of the child element*/
      String tempid = tempElement.getAttributeValue("id");
      String tempcategory = tempElement.getAttributeValue("category");
      String temporganization = tempElement.getAttributeValue("organization");
      /*Retrieve child element of tempElement*/
      org.jdom.Element contactElement = tempElement.getChild("contact");
      /*Retrieve attributes of the child element*/
      String tempaddress = contactElement.getAttributeValue("address");
      String tempphone = contactElement.getAttributeValue("phone");
      String tempcity = contactElement.getAttributeValue("city");
      String tempzip = contactElement.getAttributeValue("zip");
      /*Check if id value matches with the one specified with end-user*/
      boolean delete = (tempid.toUpperCase()).equals(id.toUpperCase());
      if(delete==true)
      {
         /*If id value matches remove the element*/
         RootElement.removeContent(tempElement);
      }
   }
   /*Obtain a XMLOutputter object*/
   org.jdom.output.XMLOutputter xmlout = new org.jdom.output.XMLOutputter();
   /*Write the updated JDOM Document to the XML document*/
   xmlout.output(JDOMDocument_1,new java.io.FileOutputStream(ypagespath));
   %>
   </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the DoDeleteEntry.jsp page. The request object in the above code retrieves the serial number of an entry that is to be deleted and parses the directorylist XML document. This creates a JDOM Document object. The code iterates through the elements of the Document object to search for the element whose id attribute matches that specified by the end-user. After the element is located, the code calls the removeContent() method of the Element object to remove the element from the JDOM Document object. Finally, the code uses the output() method of the XMLOutputter object to transform the JDOM Document object to the XML document.


Creating the User Module

The user module of the online directory application allows an end-user to search for organizations by category, city, and zip code. The user module contains the User Options, Search by Category, Search by City, and Search by Zip Code pages.

Creating the User Options Page

The User Options page of the online directory application displays hyperlinks to the Search by Category, Search by City, and Search by Zip Code pages. The UserPage.jsp file provides the User Options page of the application.

Listing 3-12 shows the content of the UserPage.jsp file:

Listing 3-12: The UserPage.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String ypagespath;%>
<%
String username, role;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("user".equals(role))
{
   /*For user role display user interface*/
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <p>&nbsp;</p>
   <!--Display User Options table-->
   <table border="1" width="46%" bgcolor="#CCCCCC">
   <tr>
   <td width="50%" ><div align="center"><font color="#990000"><b>User
   Options</b></font></div></td>
   </tr>
   <!--Display hyperlink to Category.jsp-->
   <tr>
   <td width="50%"><div align="center"><a href="Category.jsp">Search by
   category</a></div>
   <tr>
   <!--Display hyperlink to City.jsp-->
   <td width="50%"><div align="center"><a href="City.jsp">Search by
   city</a></div></td>
   </tr>
   <!--Display hyperlink to Zip.jsp-->
   <tr>
   <td width="50%"><div align="center"><a href="Zip.jsp">Search by zip
   code</a></div></td>
   </tr>
   </table>
   <br><br>
   <table border="1" width="92%" bgcolor="#CCCCCC">
   <tr>
   <td width="11%">
   <div align="center"><b><font color="#990000">Serial
   No</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Category</font></b></div>
   </td>
   <td width="15%">
   <div align="center"><b><font
   color="#990000">Organization</font></b></div>
   </td>
   <td width="26%">
   <div align="center"><b><font
   color="#990000">Address</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Phone</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">City</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">State</font></b></div>
   </td>
   <td width="14%">
   <div align="center"><b><font
   color="#990000">Zip</font></b></div>
   </td>
   </tr>
<%
try{
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/third/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the directorypath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      ypagespath = prop.getProperty("directorypath");
}
catch(Exception ex)
{
   ex.printStackTrace();
}
/*Obtain a JAXPDOMAdapter object*/
org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
/*Call he getDocument() method to parse the directorylist.xml file and obtain a Document object*/
org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new FileInputStream(ypagespath),false);
/*Create a new DOMBuilder object*/
org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
/*Call the build() method to obtain a JDOM Document*/
org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
 /*Call the getRootElement method to retrieve the root element of the XML document*/
org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
/*Retrieve all child elements of the root element as a List object*/
java.util.List UserList = RootElement.getChildren();
/*Iterate through the List object*/
for(int cntr1 = 0; cntr1 <UserList.size(); cntr1 ++)
   {
       /*Retrieve a child element, tempElement of root element*/
      org.jdom.Element tempElement = (org.jdom.Element)(UserList.get(cntr1));
      /*Retrieve attributes of the child element*/
      String tempid = tempElement.getAttributeValue("id");
      String tempcategory = tempElement.getAttributeValue("category");
      String temporganization = tempElement.getAttributeValue("organization");
      /*Retrieve child element of tempElement*/
      org.jdom.Element contactElement = tempElement.getChild("contact");
      /*Retrieve attributes of the child element*/
      String tempaddress = contactElement.getAttributeValue("address");
      String tempphone = contactElement.getAttributeValue("phone");
      String tempcity = contactElement.getAttributeValue("city");
      String tempstate = contactElement.getAttributeValue("state");
      String tempzip = contactElement.getAttributeValue("zip");
      boolean display = true;
      if(display == true)
      {
         /*For display value true, Display retrieved records*/
         %>      <tr>
         <td width="11%">
         <div align="center"><b><font
         color="#990000"><%=tempid%></font></b></div>
         </td>
         <td width="12%">
         <div align="center"><font
         color="#990000"><%=tempcategory%></font></div>
         </td>
         <td width="15%">
         <div align="center"><font
         color="#990000"><%=temporganization%></font></div>
         </td>
         <td width="26%">
         <div align="center"><font
         color="#990000"><%=tempaddress%></font></div>
         </td>
         <td width="12%">
         <div align="center"><font
         color="#990000"><%=tempphone%></font></div>
         </td>
         <td width="10%">
         <div align="center"><font
         color="#990000"><%=tempcity%></font></div>
         </td>
         <td width="10%">
         <div align="center"><font
         color="#990000"><%=tempstate%></font></div>
         </td>
         <td width="14%">
         <div align="center"><font
         color="#990000"><%=tempzip%></font></div>
         </td>
         </tr>
         <%
     }
  }
   %>
   </table>
   <br><br>
   <!--Display hyperlink to Logon.jsp-->
   <p><a href="Logon.jsp">Logout</a></p>
   <p>&nbsp;</p>
   </div>
   <div align="center">    </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the User Options page of the online directory application. The code retrieves the user ID and role values from the session object. For the user role, the code displays hyperlinks to the Category.jsp, City.jsp, and Zip.jsp files.

Figure 3-9 shows the User Options page of the online directory application:

Click To expand: This figure shows the User Options page that displays the Search by category, Search by city, and Search by zip code hyperlinks.
Figure 3-9: The User Options Page

Creating the Search by Category Page

To open the Search by Category page, an end-user needs to select the Search by category hyperlink in the User Options page. The Search by Category page allows the end-user to run a category-wise search for data. For example, the end-user can specify the Real Estate category to view data about real estate organizations. The Category.jsp page provides the Search by Category page.

Listing 3-13 shows the content of the Category.jsp file:

Listing 3-13: The Category.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String ypagespath;%>
<%
String username, role, category;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("user".equals(role))
{
   /*If user role is user, retrieve value of textfieldCategory request parameter*/
   category= request.getParameter("textfieldCategory");
   /*If category is null, initialize category with blank String*/
   if(category==null)
   {
      category="";
   }
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <!--Page design to display directory records-->
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <p><strong>Search by Category</strong> </p>
   <table width="372" border="0">
   <tr>
   <!--Display hyperlinks to Logon.jsp and UserPage.jsp-->
   <td width="132"><div align="center"><a href="Logon.jsp">Logout
   </a></div></td>
   <td width="230"><div align="center"><a href="UserPage.jsp">Back to main
   page</a></div></td>
   </tr>
   </table>
   <h3>&nbsp;</h3>
   </div>
   <div align="center">
   <!--Create form to submit data to same page-->
   <form name="form1" method="post" action="Category.jsp">
   <table border="1" width="92%" bgcolor="#CCCCCC">
   <tr>
   <td  colspan = 7>
   <!--Display Category text field and Submit button-->
   <div align="center"><font color="#990000"><b> Category :</b>
   <input type="text" name="textfieldCategory" >
   <input type="submit" name="Submit" value="Search">
   </font></div>
   </td>
   </tr>
   <!--Display table headings -->
   <tr>
   <td width="11%">
   <div align="center"><b><font color="#990000">Serial
   No</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Category</font></b></div>
   </td>
   <td width="15%">
   <div align="center"><b><font
   color="#990000">Organization</font></b></div>
   </td>
   <td width="26%">
   <div align="center"><b><font
   color="#990000">Address</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Phone</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">City</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">State</font></b></div>
   </td>
   <td width="14%">
   <div align="center"><b><font
   color="#990000">Zip</font></b></div>
   </td>
   </tr>
   <%
   try{
         /*Create a URL object to load the properties file*/
         URL url=new URL("http://127.0.0.1:8080/third/path.properties");
         /*Open URL connection*/
         URLConnection ucon=url.openConnection();
         /*Retrieve the directorypath property*/
         Properties prop = new Properties();
         prop.load(ucon.getInputStream());
         ypagespath = prop.getProperty("directorypath");
      }
   catch(Exception ex)
   {
      ex.printStackTrace();
   }
   /*Obtain a JAXPDOMAdapter object*/
   org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
   /*Call he getDocument() method to parse the directorylist.xml file and obtain a Document object*/
   org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new FileInputStream(ypagespath),false);
   /*Create a new DOMBuilder object*/
   org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
   /*Call the build() method to obtain a JDOM Document*/
   org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
    /*Call the getRootElement method to retrieve the root element of the XML document*/
   org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
   /*Retrieve all child elements of the root element as a List object*/
   java.util.List UserList = RootElement.getChildren();
   /*Iterate through the List object*/
   for(int cntr1 = 0; cntr1 <UserList.size(); cntr1 ++)
   {
      /*Retrieve a child element, tempElement of root element*/
      org.jdom.Element tempElement = (org.jdom.Element)(UserList.get(cntr1));
      /*Retrieve attributes of the child element*/
      String tempid = tempElement.getAttributeValue("id");
      String tempcategory = tempElement.getAttributeValue("category");
      String temporganization = tempElement.getAttributeValue("organization");
      /*Retrieve child element of tempElement*/
      org.jdom.Element contactElement = tempElement.getChild("contact");
      /*Retrieve attributes of the child element*/
      String tempaddress = contactElement.getAttributeValue("address");
      String tempphone = contactElement.getAttributeValue("phone");
      String tempcity = contactElement.getAttributeValue("city");
      String tempstate = contactElement.getAttributeValue("state");
      String tempzip = contactElement.getAttributeValue("zip");
      boolean display = true;
      /*For a blank category, mark boolean display as true*/
      if(category.equals(""))
   {
      display = true;
   }
            else
   {
      /*Check for matching categories*/
      int categoryposition=(tempcategory.toUpperCase()).indexOf(category.toUpperCase(),0);
      /*If no matching categories exist, mark display as false*/
      if(categoryposition == -1)
      display = false;
   }
   if(display == true)
   {
      /*For display value true, Display retrieved records*/
      %>
      <tr>
      <td width="11%">
      <div align="center"><b><font
      color="#990000"><%=tempid%></font></b></div>
      </td>
      <td width="12%">
      <div align="center"><font
      color="#990000"><%=tempcategory%></font></div>
      </td>
      <td width="15%">
      <div align="center"><font
      color="#990000"><%=temporganization%></font></div>
      </td>
      <td width="26%">
      <div align="center"><font
      color="#990000"><%=tempaddress%></font></div>
      </td>
      <td width="12%">
      <div align="center"><font
      color="#990000"><%=tempphone%></font></div>
      </td>
      <td width="10%">
      <div align="center"><font
      color="#990000"><%=tempcity%></font></div>
      </td>
      <td width="10%">
      <div align="center"><font
      color="#990000"><%=tempstate%></font></div>
      </td>
      <td width="14%">
      <div align="center"><font
      color="#990000"><%=tempzip%></font></div>
      </td>
      </tr>
      <%
   }
  }
   %>
   </table>
   </form>
   </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the Search by Category page of the online directory application. The code parses the yellowpages XML document to provide the user interface to display directoryentries. The user interface also displays a Category text field and a Search button. When an end-user specifies a category and clicks Search, the code uses the request object to obtain the category value. The getDocument() method parses the XML document to obtain a JDOM Document object. The getRootElement() method of the Document object returns an Element object. The getChildren() method of the Element object retrieves a list of objects that contains subelements of the root element. The code searches for all elements whose category attribute matches the value specified by the end-user. Finally, the code displays the result set in tabular format.

Figure 3-10 shows the Search by Category page of the online directory application:

Click To expand: This figure shows the Search by Category page of the online directory application. It contains a Category text field in which an end-user can specify a category to view relevant data.
Figure 3-10: The Search by Category Page

Creating the Search by City Page

An end-user can search for organizations located in a particular city using the Search by City page of the online directory application. This page contains a City text field and a Search button. When an end-user specifies a city name and clicks Search, the Search by City page displays information about organizations located in that city. The City.jsp page provides the Search by City page of the online directory application.

Listing 3-14 shows the content of the City.jsp file:

Listing 3-14: The City.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String ypagespath;%>
<%
String username, role, city;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("user".equals(role))
{
   /*If user role is user, retrieve value of textfieldCity request parameter*/
   city= request.getParameter("textfieldCity");
   /*If city is null, initialize city variable with blank String*/
   if(city==null)
   {
      city="";
   }
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <!--Page design to display directory records-->
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <p><strong>Search by City</strong> </p>
   <table width="372" border="0">
   <tr>
   <!--Display hyperlinks to Logon.jsp and UserPage.jsp-->
   <td width="132"><div align="center"><a href="Logon.jsp">Logout
   </a></div></td>
   <td width="230"><div align="center"><a href="UserPage.jsp">Back to main
   page</a></div></td>
   </tr>
   </table>
   </div>
   <div align="right"></div>
   <div align="center">
   <!--Create form to submit data to same page-->
   <form name="form1" method="post" action="City.jsp">
   <table border="1" width="92%" bgcolor="#CCCCCC">
   <tr>
   <!--Display City text field and Submit button-->
   <td  colspan = 7><div align="center"><font
   color="#990000"><b>City:</b>
   <input type="text" name="textfieldCity" >
   <input type="submit" name="Submit" value="Search">
   </font></div>
   </td>
   </tr>
   <!--Display table headings -->
   <tr>
   <td width="11%">
   <div align="center"><b><font color="#990000">Serial
   No</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Category</font></b></div>
   </td>
   <td width="15%">
   <div align="center"><b><font
   color="#990000">Organization</font></b></div>
   </td>
   <td width="26%">
   <div align="center"><b><font
   color="#990000">Address</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Phone</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">City</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">State</font></b></div>
   </td>
   <td width="14%">
   <div align="center"><b><font
   color="#990000">Zip</font></b></div>
   </td>
   </tr>
   <%
   try
   {
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/third/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the directorypath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      ypagespath = prop.getProperty("directorypath");
   }
   catch(Exception ex)
   {
      ex.printStackTrace();
   }
   /*Obtain a JAXPDOMAdapter object*/
   org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
   /*Call he getDocument() method to parse the directorylist.xml file and obtain a Document object*/
   org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new
   FileInputStream(ypagespath),false);
   /*Create a new DOMBuilder object*/
   org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
   /*Call the build() method to obtain a JDOM Document*/
   org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
   /*Call the getRootElement method to retrieve the root element of the XML document*/
   org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
   /*Retrieve all child elements of the root element as a List object*/
   java.util.List UserList = RootElement.getChildren();
   /*Iterate through the List object*/
   for(int cntr1 = 0; cntr1 <UserList.size(); cntr1 ++)
   {
      /*Retrieve a child element, tempElement of root element*/
      org.jdom.Element tempElement = (org.jdom.Element)(UserList.get(cntr1));
      /*Retrieve attributes of the child element*/
      String tempid = tempElement.getAttributeValue("id");
      String tempcategory = tempElement.getAttributeValue("category");
      String temporganization = tempElement.getAttributeValue("organization");
      /*Retrieve child element of tempElement*/
      org.jdom.Element contactElement = tempElement.getChild("contact");
      /*Retrieve attributes of the child element*/
      String tempaddress = contactElement.getAttributeValue("address");
      String tempphone = contactElement.getAttributeValue("phone");
      String tempcity = contactElement.getAttributeValue("city");
      String tempstate = contactElement.getAttributeValue("state");
      String tempzip = contactElement.getAttributeValue("zip");
      boolean display = true;
      /*For a blank city, mark boolean display as true*/
      if(city.equals(""))
      {
         display = true;
      }
      else
      {
        /*Check for matching cities*/
      int cityposition=(tempcity.toUpperCase()).indexOf(city.toUpperCase(),0);
         /*If no matching cities exist, mark display as false*/
      if(cityposition == -1)
           display = false;
      }
      if(display == true)
      {
      /*For display value true, Display retrieved records*/
      %>
      <tr>
      <td width="11%">
      <div align="center"><b><font
      color="#990000"><%=tempid%></font></b></div>
      </td>
      <td width="12%">
      <div align="center"><font
      color="#990000"><%=tempcategory%></font></div>
      </td>
      <td width="15%">
      <div align="center"><font
      color="#990000"><%=temporganization%></font></div>
      </td>
      <td width="26%">
      <div align="center"><font
      color="#990000"><%=tempaddress%></font></div>
      </td>
      <td width="12%">
      <div align="center"><font
      color="#990000"><%=tempphone%></font></div>
      </td>
      <td width="10%">
      <div align="center"><font
      color="#990000"><%=tempcity%></font></div>
      </td>
      <td width="10%">
      <div align="center"><font
      color="#990000"><%=tempstate%></font></div>
      </td>
      <td width="14%">
      <div align="center"><font
      color="#990000"><%=tempzip%></font></div>
      </td>
      </tr>
      <%
   }
  }
   %>
   </table>
   </form>
   </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the Search by City page. This code displays a City text field and a Search button. When an end-user specifies a city name and clicks Search, the code retrieves the city value from the request object. The code uses JDOM to parse the directorylist XML document to access the elements whose city attribute matches the value specified by the end-user. The code then displays the result set in tabular format.

Figure 3-11 shows the Search by City page of the online directory application:

Click To expand: This figure shows the Search by City page of the online directory application that contains a City text field and a Search button.
Figure 3-11: The Search by City Page

Creating the Search by Zip Code Page

The Search by Zip Code page of the online directory application allows an end-user to run a zip code search for organizations. The Zip.jsp page provides the Search by Zip Code page of the online directory application.

Listing 3-15 shows the content of the Zip.jsp file:

Listing 3-15: The Zip.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<%!String ypagespath, zip;%>
<%
String username, role, city;
/*Retrieve user name and role from session*/
username= (String)session.getAttribute("username");
role = (String)session.getAttribute("role");
/*Check whether user name and role values exists*/
if(username==null || role==null)
{
   /*If user name or role value is null, forward to Logon.jsp*/
   %>
   <jsp:forward page = "Logon.jsp"/>
   <%
}
else if("user".equals(role))
{
   /*If user role is user, retrieve value of ttextfieldZip request parameter*/
   zip= request.getParameter("textfieldZip");
   /*If zip is null, initialize zip variable with blank String*/
   if(zip==null)
   {
      zip="";
   }
   %>
   <html>
   <head>
   <title>Online Directory</title>
   </head>
   <!--Page design to display directory records-->
   <body bgcolor="#CCFFCC">
   <div align="center">
   <table width="93%" height="79" border="1">
   <tr>
   <td width="100%" height="55" align="center" bgcolor="#C0C0C0"><p
   align="center"><b><font color="#800000" face="Book Antiqua" size="5">Online
   Directory</font></b></td>
   </tr>
   </table>
   <p><strong>Search by Zip Code </strong></p>
   <table width="372" border="0">
   <!--Display hyperlinks to Logon.jsp and UserPage.jsp-->
   <tr>
   <td width="132"><div align="center"><a href="Logon.jsp">Logout
   </a></div></td>
   <td width="230"><div align="center"><a href="UserPage.jsp">Back to main
   page</a></div></td>
   </tr>
   </table>
   </div>
   <!--Create form to submit data to same page-->
   <div align="center"><form name="form1" method="post" action="Zip.jsp">
   <table border="1" width="92%" bgcolor="#CCCCCC">
   <tr>
   <td  colspan = 7>
   <!--Display Zip Code text field and Submit button-->
   <div align="center"><font color="#990000"><b> Zip Code:</b>
   <input type="text" name="textfieldZip" >
   <input type="submit" name="Submit" value="Search">
   </font></div>
   </td>
   </tr>
   <!--Display table headings -->
   <tr>
   <td width="11%">
   <div align="center"><b><font color="#990000">Serial
   No</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Category</font></b></div>
   </td>
   <td width="15%">
   <div align="center"><b><font
   color="#990000">Organization</font></b></div>
   </td>
   <td width="26%">
   <div align="center"><b><font
   color="#990000">Address</font></b></div>
   </td>
   <td width="12%">
   <div align="center"><b><font
   color="#990000">Phone</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">City</font></b></div>
   </td>
   <td width="10%">
   <div align="center"><b><font
   color="#990000">State</font></b></div>
   </td>
   <td width="14%">
   <div align="center"><b><font
   color="#990000">Zip</font></b></div>
   </td>
   </tr>
   <%
   try
   {
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/third/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the directorypath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      ypagespath = prop.getProperty("directorypath");
   }
   catch(Exception ex)
   {
      ex.printStackTrace();
   }
   /*Obtain a JAXPDOMAdapter object*/
   org.jdom.adapters.JAXPDOMAdapter JAXPDOMAdapter_1 = new org.jdom.adapters.JAXPDOMAdapter();
   /*Call he getDocument() method to parse the directorylist.xml file and obtain a Document object*/
   org.w3c.dom.Document Document_1 = JAXPDOMAdapter_1.getDocument(new
   FileInputStream(ypagespath),false);
   /*Create a new DOMBuilder object*/
   org.jdom.input.DOMBuilder DOMBuilder_1 = new org.jdom.input.DOMBuilder();
   /*Call the build() method to obtain a JDOM Document*/
   org.jdom.Document JDOMDocument_1 = DOMBuilder_1.build(Document_1);
   /*Call the getRootElement method to retrieve the root element of the XML document*/
   org.jdom.Element RootElement = JDOMDocument_1.getRootElement();
   /*Retrieve all child elements of the root element as a List object*/
   java.util.List UserList = RootElement.getChildren();
   /*Iterate through the List object*/
   for(int cntr1 = 0; cntr1 <UserList.size(); cntr1 ++)
   {
      /*Retrieve a child element, tempElement of root element*/
      org.jdom.Element tempElement = (org.jdom.Element)(UserList.get(cntr1));
      /*Retrieve attributes of the child element*/
      String tempid = tempElement.getAttributeValue("id");
      String tempcategory = tempElement.getAttributeValue("category");
      String temporganization = tempElement.getAttributeValue("organization");
      /*Retrieve child element of tempElement*/
      org.jdom.Element contactElement = tempElement.getChild("contact");
      /*Retrieve attributes of the child element*/
      String tempaddress = contactElement.getAttributeValue("address");
      String tempphone = contactElement.getAttributeValue("phone");
      String tempcity = contactElement.getAttributeValue("city");
      String tempstate = contactElement.getAttributeValue("state");
      String tempzip = contactElement.getAttributeValue("zip");
      boolean display = true;
      /*For a blank zip, mark boolean display as true*/
      if(zip.equals(""))
      {
         display = true;
      }
      else
      {
         /*Check for matching zip codes*/
         int zipposition=(tempzip.toUpperCase()).indexOf(zip.toUpperCase(),0);
         /*If no matching zip code exist, mark display as false*/
         if(zipposition == -1)
         display = false;
      }
      if(display == true)
      {
         /*For display value true, Display retrieved records*/
         %>
         <tr>
         <td width="11%">
         <div align="center"><b><font
         color="#990000"><%=tempid%></font></b></div>
         </td>
         <td width="12%">
         <div align="center"><font
         color="#990000"><%=tempcategory%></font></div>
         </td>
         <td width="15%">
         <div align="center"><font
         color="#990000"><%=temporganization%></font></div>
         </td>
         <td width="26%">
         <div align="center"><font
         color="#990000"><%=tempaddress%></font></div>
         </td>
         <td width="12%">
         <div align="center"><font
         color="#990000"><%=tempphone%></font></div>
         </td>
         <td width="10%">
         <div align="center"><font
         color="#990000"><%=tempcity%></font></div>
         </td>
         <td width="10%">
         <div align="center"><font
         color="#990000"><%=tempstate%></font></div>
         </td>
         <td width="14%">
         <div align="center"><font
         color="#990000"><%=tempzip%></font></div>
         </td>
         </tr>
         <%
      }
  }
   %>
   </table>
   </form>
   </div>
   </body>
   </html>
   <%
}
%>
End example

Download this listing.

The above code creates the Search by Zip Code page of the online directory application. The code provides a Zip Code text field and a Search button. When an end-user specifies a zip code and clicks Search, the code retrieves the zip code value from the request object. The code uses JDOM to parse the directorylist XML document to access the elements whose zip code attribute matches the value specified by the end-user. The code then displays the result set in tabular format.

Figure 3-12 shows the Search by Zip Code page of the online directory application:

Click To expand: This figure shows the Search by Zip Code page of the online directory application that displays the Zip Code text field and the Search button.
Figure 3-12: The Search by Zip Code Page


Creating the Property File

The property file of the online directory application stores the path to the XML files of the application. The following code shows the path.properties property file of the application:

userlistpath=c:/Chp3/code/xml/userlist.xml

directorypath=c:/Chp3/code/xml/directorylist.xml

The above code contains the following properties:

  • userlistpath: Specifies the path to the userlist.xml file.

  • yellowpageslistpath: Specifies the path to the directorylist.xml file.

Note

You need to change the values of the userlistpath and yellowpageslistpath properties of the path.properties file to the full path name of the XML files stored in the computer.


Unit Testing

You need to deploy and test the online directory application on the Sun Java System Application Server Platform Edition 8. You can download this application server from:

http://java.sun.com/j2ee/1.4/download.html

Note

To install the Sun Java System Application Server Platform Edition 8, you need to install Java 2 Standard Edition (J2SE) 1.4.2 on the computer.

To test the application, you need to include the JDOM Java Archive (JAR) file in the application server classpath. You can download the binary distribution of JDOM from http://www.jdom.org/downloads/ to obtain the jdom.jar file.

You need to copy the jdom.jar file from the build directory of your JDOM binary installation directory to:

  • <ApplicationServer_Default_Installation>/AppServer/lib

  • <ApplicationServer_Default_Installation>/AppServer/Domains/Domain1/lib

To ensure that the jdom.jar file is loaded to the application server classpath, restart the application server after you copy the jdom.jar file in the lib directories.

You can use the deploytool utility to deploy the online directory application to the Sun Java System Application Server Platform Edition 8.

To deploy the online directory application:

  1. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Start Default Server from the Start menu to start the application server.

  2. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Deploytool from the Start menu to open the Deployment Tool window.

  3. Select New->Application from the File menu of the Deployment Tool window. The New Application dialog box appears.

  4. Click Browse in the New Application dialog box to display another New Application dialog box.

  5. Select the directory where you want to save the .ear file in the Look In combo box.

  6. Enter the name of the .ear file as OnlineDirectoryApp in the File Name text box, as shown in Figure 3-13:

    Click To expand: This figure shows the New Application dialog box, which contains the Look In drop-down list and File Name text field in which you can specify the name of the application file and the location to store it.
    Figure 3-13: The New Application Dialog Box

  7. Click the New Application button to return to the previous New Application dialog box.

  8. Click OK to create the new application.

  9. Select New->Web Component from the File menu of the Deployment Tool window. The New Web Application Wizard-Introduction dialog box appears.

  10. Click Next. The New Web Application Wizard-WAR File dialog box appears.

  11. Click Edit Contents in the New Web Application Wizard-WAR File dialog box. The Edit Contents of WebApp dialog box appears.

  12. Select all the JSP files and the path.properties file of the application in the Available Files pane and click Add. The Contents of WebApp pane displays the added files, as shown in Figure 3-14:

    Click To expand: This figure shows the Edit Contents of WebApp dialog box that displays the files of the online directory application.
    Figure 3-14: The Edit Contents of WebApp Dialog Box

  13. Click OK to add the files to the Web application Web Archive (WAR) file.

  14. Click Next in the New Web Application Wizard-WAR File dialog box. The New Web Application Wizard-Choose Component Type dialog box appears.

  15. Select the JSP Page radio button and click Next. The New Web Application Wizard-Component General Properties dialog box appears.

  16. Select Logon.jsp from the JSP Filename drop-down list. The remaining fields get automatically populated with values. Figure 3-15 shows the New Web Application Wizard-Component General Properties dialog box:

    Click To expand: This figure shows the New Web Application Wizard-Component General Properties dialog box in which you specify the main page of your application.
    Figure 3-15: The New Web Application Wizard-Component General Properties Dialog Box

  17. Click Finish.

  18. In the Deployment Tool window, specify third as the context root of your application in the Context Root text field, as shown in Figure 3-16:

    Click To expand: This figure shows the Context Root text field of the Deployment Tool window in which you can specify the context root of your application.
    Figure 3-16: The Deployment Tool Window

  19. Select Save from the File menu of the Deployment Tool window to save the application.

  20. Select Deploy from the Tools menu. The Deploy Module OnlineDirectoryApp dialog box appears.

  21. Specify the application server user name and password in the User Name and Password fields and click OK.

  22. The Distribute Module dialog box appears indicating the successful deployment of the application.

To test the deployed application:

  1. Type the following URL in the address bar of the browser:

    http://localhost:8080/third/Logon.jsp

  2. The User Logon page of the online directory application appears. Specify admin in both the User ID and Password fields, as shown in Figure 3-17:

    Click To expand: This figure shows the User Logon page that displays the User ID and Password fields, in which you can specify logon information.
    Figure 3-17: Specifying User ID and Password

  3. Click the Logon button. The user interface of the DoLogon JSP page displays the hyperlink to the Administrator Options page, as shown in Figure 3-18:

    Click To expand: This figure shows the user interface of the DoLogon JSP page that displays a welcome message and the Go to admin page hyperlink.
    Figure 3-18: The DoLogon JSP page for Administrator Role

  4. Select the Go to admin page hyperlink. The Administrator Options page appears, as shown in Figure 3-19:

    Click To expand: This figure shows the Administrator Options page that displays the Logout, Add entry, and Delete entry hyperlinks.
    Figure 3-19: Selecting the Go to admin page Hyperlink

  5. Select the Add entry hyperlink. The Add Entry page appears.

  6. In the Add Entry page, specify information about an organization you want to add to the directorylist.xml file, as shown in Figure 3-20:

    Click To expand: This figure shows the Add Entry page in which you can specify information about an organization in the Serial No, Category, Organization, Address, Phone No, City, State and Zip Code text fields.
    Figure 3-20: Specifying Information

  7. Click the Add button. The DoAddEntry JSP page displays a success message, as shown in Figure 3-21:

    Click To expand: This figure shows the user interface of the DoAddEntry JSP page that displays the Entry successfuly added. message along with the Back to main page and Add more entry hyperlinks.
    Figure 3-21: User Interface of the DoAddEntry JSP Page

  8. Select the Add more entry hyperlink to add more entries in the Add Entry page.

  9. In the Administrator page, select the Delete entry hyperlink. The Delete Entry page appears, which displays all entries of the directory, as shown in Figure 3-22:

    Click To expand: This figure shows the Delete Entry page that displays entries and Delete buttons to delete entries.
    Figure 3-22: Deleting an Entry

  10. Click any Delete button to delete its corresponding entry. The DoDeleteEntry JSP page displays a message to indicate that the entry has been successfuly deleted, as shown in Figure 3-23:

    Click To expand: This figure shows the user interface of the DoDeleteEntry JSP page that displays the message, Entry successfuly deleted.
    Figure 3-23: User Interface of the DeleteEntry JSP Page

  11. Select the Logout hyperlink to logout from the application.

  12. In the User Logon page, select the New user hyperlink to register as a new user. The User Registration page appears.

  13. Specify registration information, as shown in Figure 3-24:

    Click To expand: This figure shows the User Registration page in which you can specify information to register with the application.
    Figure 3-24: The User Registration Page

  14. Click the Submit button. The RegisterUser JSP page displays a message that indicates successful registration.

  15. In the User Logon page, specify the user name and password with which you had registered and click Logon. The user interface of the DoLogon JSP page provides a hyperlink to the User Options page, as shown in Figure 3-25:

    Click To expand: This figure shows the user interface of the DoLogon JSP page that displays a logon success message and the Go to user page hyperlink.
    Figure 3-25: User Interface of the DoLogon JSP Page

  16. Select the Go to user page hyperlink. The User Options page appears, as shown in Figure 3-26:

    Click To expand: This figure shows the User Options page that displays the Search by category, Search by city, and Search by zip code hyperlinks.
    Figure 3-26: Selecting a Hyperlink

  17. Select the Search by category hyperlink. The Search by Category page appears and displays entries. Specify a category name in the Category text field to view data about organizations listed under that category. Figure 3-27 shows the Search by Category page of the online directory application:

    Click To expand: This figure shows the Search by Category page that contains a Category text field. You can specify a category to view information about organizations listed under that category.
    Figure 3-27: Specifying a Category

  18. Click the Search button. The Search by Category page displays information about organizations listed under the specified category, as shown in Figure 3-28:

    Click To expand: This figure shows the Search by Category page that displays information about organizations listed under the category specified by the end-user.
    Figure 3-28: Organizations for a Specified Category

  19. Select the Search by city and Search by zip code hyperlinks in the User Options page to search for organizations using the city and zip code criteria.

  20. Click Logout in the User Options page to logout from the application.


Point 4: Generating Dynamic XML Content in JSP Applications

JSP applications can access and display data stored in XML documents. To generate dynamic XML content, JSP applications use the application/xml value of the content-type attribute of a JSP page directive. JSP applications can display XML data in XML and HTML formats. To display data in HTML format, JSP applications use the Extensible Stylesheet Language (XSL) style sheet.

This chapter describes how to create an online technical support application that allows end users to view and reply to technical queries. End users can store the query information in XML or HTML format. They can also download the query information as an XML file.

Creating the Online Technical Support Application

The online technical support application allows end users to view and post technical queries. Administrators are authorized to reply to these queries. The application uses an XSL style sheet to allow end users to view query information in HTML format. To display query information in XML format, the application dynamically generates the relevant XML content during run time. The application also allows end users to download the dynamically generated XML content and save it as an XML file.

The XML files of the online technical support application are:

  • userlist.xml: Contains information about end user logon ID and password.

  • querylist.xml: Contains information about end user queries.

The JSP files of the online technical support application provide the user interfaces of the application. These JSP files can be grouped under the following modules, based on their functioning:

  • Logon module: Authenticates end user information to allow access to the user and administrator modules. The files of the logon module are:

    • Logon.jsp: Provides a user interface that displays the User ID and Password text fields.

    • DoLogon.jsp: Authenticates end user information using data stored in the userlist.xml file.

    • DoLogout.jsp: Invalidates the current user session.

  • User module: Allows end users to post new queries. The files of the user module are:

    • UserPage.jsp: Displays links to the NewQuery.jsp and ViewQueryList.jsp files.

    • NewQuery.jsp: Displays the fields that enable end users to post new queries.

  • Administrator module: Allows the administrator to post replies to queries. The files for the administrator module are:

    • AdminPage.jsp: Displays links to the QueryReply.jsp and ViewQueryList.jsp files.

    • QueryReply.jsp: Displays the fields that enable an administrator to post a reply to a query.

  • View query module: Contains files that are common to both user and administrator modules. The view query module enables end users to view query information in HTML or XML format. This module also allows end users to save query information as XML files. The files of the view query module are:

    • ViewQueryList.jsp: Displays the fields that allow an end user to view a query and its reply.

    • ViewQuery.jsp: Uses the QueryXMLGenerator class to dynamically generate the XML document for a query.

    • QueryXMLGenerator.java: Provides content for the XML document the ViewQuery JSP page generates.

    • technicalhelpdesk.xsl: Provides the dynamically generated XML document in HTML format.

Figure 4-1 shows the architecture of the online technical support application:

Click To expand: This figure shows the JSP pages the online technical support application uses and the sequence in which it uses them.
Figure 4-1: Architecture of the Online Technical Support Application


Creating the XML Files

The online technical support application uses the userlist and querylist XML documents to store end user and query data.

The userlist XML document contains the userlist root element that encloses user elements. A user element contains the name and password attributes that represent the user name and password of an end user. Listing 4-1 shows the content of the userlist.xml file:

Listing 4-1: The userlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<userlist>
   <user name="Peter" password="peter">
   </user>
   <user name="admin" password="admin">
   </user>
</userlist>
End example

Download this listing.

The querylist XML document contains information about queries stored in query elements within the querylist root element.

Listing 4-2 shows the content of the querylist.xml file:

Listing 4-2: The querylist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<querylist>
<query msg="How can I display XML content from JSP page?" postedon="6/26/2004"
title="JSP-XML" user="Peter">
<received msg="Thanks for your query. The administrator will address it promptly."/>
</query>
</querylist>
End example

Download this listing.

The above code contains the querylist root element that has query elements. A query element contains the msg, postedon, title, and user attributes. The msg attribute contains the end user query. The postedon attribute contains the date on which the query was posted. The title and user attributes contain the title of the query and the user ID of the user who posted the query. Each query element contains a received element that is generated by the application to acknowledge receipt of the query.


Creating the Logon Module

The logon module of the application authenticates end user information before allowing access to the user and administrator modules. The logon module contains the Logon, DoLogon, and DoLogout JSP pages.

Creating the Logon JSP Page

The Logon JSP page of the online technical support application provides the user ID and password fields to accept end user logon information. Listing 4-3 shows the content of the Logon.jsp file:

Listing 4-3: The Logon.jsp File
Start example
<%
/*Use request object to retrieve error parameter*/
String error=request.getParameter("error");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
</style></head>
<body text="#000000">
<div align="center">
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online Technical Support
</em></strong></font></h2></td>
</tr>
</table>
<p><font size="5"></font></p>
<%
if("error".equals(error))
{
   /*If error parameter contains the value, error, display message to indicate invalid logo on*/
    <%
   <p><font size="3"><b><font color="#E24907">Invalid user name or
   password. Please Log on again.</font></b></font></p>
  %>
}
%>
<!--Page design to display User ID and Password fields. Submit form to DoLogon.jsp-->
<form name="form1" method="post" action="DoLogon.jsp">
<table width="75%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="20%">&nbsp;</td>
<td width="24%">
<div align="center"><strong><font size="3">User
ID:</font></strong></div></td>
<td width="53%"><font size="3">
<input type="text" name="textfield_logon"/>
</font></td>
<td width="3%">&nbsp;</td>
</tr>
<tr>
<td width="20%" height="45">&nbsp;</td>
<td width="24%" height="45">
<div
align="center"><strong>Password:</strong>&nbsp;&nbsp;&
nbsp;</div></td>
<td width="53%" height="45">
<input type="password" name="textfield_password"/>
</td>
<td width="3%" height="45">&nbsp;</td>
</tr>
<tr>
<td width="20%">&nbsp;</td>
<td width="24%">
<div align="right">
<input type="submit" name="Submit" value="Logon" class="button"/>
</div>
</td>
<td width="53%">
<div align="left">
<input type="reset" name="Reset" value="Reset" class="button"/>
</div>
</td>
<td width="3%">&nbsp;</td>
</tr>
</table>
</form>
<p>&nbsp;</p><p><font size="3"></font></p>
<p>&nbsp;</p>
<p></p>
<p></p>
</div>
</body>
</html>
End example

Download this listing.

The above code creates the Logon page with an HTML form that contains the User ID and Password fields. When clicked, the Submit button submits the field values to the DoLogon JSP page.

Figure 4-2 shows the user interface of the Logon JSP page:

Click To expand: This figure shows the Logon page of the online technical support application that displays the User ID and Password fields in which an end user can specify logon information.
Figure 4-2: User Interface of the Logon JSP Page

Creating the DoLogon and DoLogout JSP Pages

The DoLogon JSP page authenticates logon information of end users using data stored in the userlist.xml file. After authentication, the DoLogon JSP page provides access to the user or administrator modules, based on the role assigned to the end user. Listing 4-4 shows the content of the DoLogon.jsp file:

Listing 4-4: The DoLogon.jsp File
Start example
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Online Technical Support</title>
</head>
<body>
<!--Import necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.util.*, java.io.*, org.w3c.dom.*"%>
<%
/*Retrieve user ID and password from request object*/
String userid=request.getParameter("textfield_logon");
String password=request.getParameter("textfield_password");
/*If user ID and password value is admin, store user ID and session*/
if("admin".equals(userid) && "admin".equals(password))
{
   session.setAttribute("userid", userid);
   /*Forward request to AdminPage.jsp for user ID and password value admin*/
   <%
   <jsp:forward page="AdminPage.jsp"/>
   %>
}
else
{
   /*Create a URL object to load the properties file*/
   URL url=new URL("http://127.0.0.1:8080/fourth/path.properties");
   /*Open URL connection*/
   URLConnection ucon=url.openConnection();
   /*Retrieve userlistpath value from path.properties file*/
   Properties prop = new Properties();
   prop.load(ucon.getInputStream());
   String userpath = prop.getProperty("userlistpath");
   /*Obtain a DocumentBuilder object by calling the newInstance() method*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the userlist XML document*/
   Document doc = docb.parse(new FileInputStream(userpath));
   String tempuser, temppassword;
   NamedNodeMap nnp;
   Node n;
   boolean success = false;
   tempuser="";
   temppassword="";
   /*Obtain a NodeList object that contains nodes corresponding to the user elements*/
   NodeList nodelist1 = doc.getElementsByTagName("user");
   /*Iterate through the NodelList object*/
   for(int int_1=0;int_1 < nodelist1.getLength(); int_1 ++)
   {
      /*Retrieve values of name and password attributes from nodes*/
      nnp=(nodelist1.item(int_1)).getAttributes();
      n=nnp.getNamedItem("name");
      tempuser=(n.getNodeValue());
      n=nnp.getNamedItem("password");
      temppassword =(n.getNodeValue());
      /*Compare name and password attributes of nodes with end user specified name and password*/
      if(tempuser.equals(userid)&& temppassword.equals(password))
      {
         success=true;
      }
   }
   if (success==true)
   {
      /*Store query parameter value to session*/
      session.setAttribute("userid", userid);
      %>
      <!--Page design to display hyperlink to UserPage.jsp-->
      <table width="830" height="71" border="0">
      <tr>
      <td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
      color="#000080" size="5"><strong><em>Online Technical Support
      </em></strong></font></h2></td>
      </tr>
      </table>
      <p align="center"><b></b></p>
      <table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
      <tr>
      <td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
      color="#333333"><b>User </b></font></div></td>
      <td width="104" bgcolor="#FFFFFF" height="1">
      <div align="center"><%=userid%></div></td>
      </tr>
      </table>
      <div align="justify">
      <table border="1" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
      left: 638px; top: 105px; width: 150" >
      <tr>
      <td height="18" bgcolor="#FFFFFF"><div align="center"><font
      color="#FFFFFF"><b><a
      href="DoLogout.jsp">Logout</a></b></font></div></td>
      </tr>
      <tr>
      <td height="18" bgcolor="#FFFFFF"><div align="center"><b>
      <a href="UserPage.jsp">
      Go to main page</a></b></div></td>
      </tr>
      </table>
      </div>
      </body>
      </html>
      <%
   }
   else
   {
      /*If authentication fails, forward request to Logon.jsp with error parameter*/
       <%
      <jsp:forward page="Logon.jsp">
      <jsp:param name="error" value="error"></jsp:param>
      </jsp:forward>
     %>
   }
}
%>
End example

Download this listing.

The above code creates the DoLogon JSP page. The code uses the request object to obtain end user logon information. To authenticate the logon information, the code uses the Document Object Model (DOM) to obtain a DocumentBuilder object. The parse() method of the DocumentBuilder object parses the userlist.xml file. The parse() method returns a Document object that represents the userlist.xml file as an object tree in the memory. The code iterates through the nodes of the object tree to authenticate the logon information. For an authenticated user with user ID admin, the code forwards the request to the AdminPage JSP page. For other users, the code displays a hyperlink to the UserPage.jsp file.

The DoLogout JSP page of the application terminates the current session and forwards the request object to the Logon page. Listing 4-5 shows the content of the DoLogout.jsp file:

Listing 4-5: The DoLogout.jsp File
Start example
<%
/*Invalidate current session*/
session.setAttribute("userid","");
session.invalidate();
%>
<!--Forward request to Logon.jsp-->
<jsp:forward page="Logon.jsp"/>
End example

Download this listing.

The above code uses the invalidate() method of the session object to invalidate the current session. The JSP forward action forwards the request to the Logon.jsp page.


Creating the User Module

The user module of the online technical support application allows end users to post queries for technical support. The user module contains the UserPage.jsp and NewQuery.jsp files that provide the User Options and New Query pages.

Creating the User Options Page

The User Options page displays the hyperlinks an end user can select to post a new query and view query replies. The UserPage JSP provides the User Options page of the application.

Listing 4-6 shows the content of the UserPage.jsp file:

Listing 4-6: The UserPage.jsp File
Start example
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>User Options</title>
</head>
<body>
<!--Page Design-->
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online Technical Support
</em></strong></font></h2></td>
</tr>
</table>
<p align="center"><b></b></p>
<table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
<!--Display user ID from session-->
<tr>
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font color="#000000"><b>User </b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1">
<div align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
</table>
<div align="justify">
<!--Display hyperlinks to DoLogout.jsp and UserPage.jsp files-->
<table border="1" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 663px; top: 121px; width: 150">
<tr>
<td height="18" bgcolor="#FFFFFF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<tr>
<td height="18" bgcolor="#FFFFFF"><div align="center"><b>
<a href="UserPage.jsp">
Go to main page</a></b></div></td>
</tr>
</table>
</div>
<p align="center">&nbsp;</p>
<div align="justify">
<!--Display User Options table-->
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 262px; top: 255px; width: 300">
<tr>
<td bgcolor="#FFFFFF">
<p align="center"><b><font color="#FF0000">User
Options</font></b></p>
</td>
</tr>
<!--Display hyperlink to NewQuery.jsp file-->
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="NewQuery.jsp">Post a new Query</a></b></i></div></td>
</tr>
<!--Display hyperlink to ViewQueryList.jsp file-->
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="ViewQueryList.jsp">View query list</a></b></i></div></td>
</tr>
</table>
</div>
</body>
</html>
End example

Download this listing.

The above code creates the User Options page of the online technical support application. This code displays the hyperlinks to the NewQuery.jsp and ViewQueryList.jsp files. The code also displays the Logout hyperlink to the DoLogout.jsp file.

Figure 4-3 shows the User Options page of the online technical support application:

Click To expand: This figure shows the User Options page that contains the Logout, Post a new query, and View query list hyperlinks.
Figure 4-3: The User Options Page

Creating the New Query Page

The New Query page of the online technical support application displays the fields in which an end user can specify information about a new query, such as title, date, and query content. When an end user clicks the Submit button to post the query, the New Query JSP page saves the query to the querylist.xml file. The NewQuery.jsp file provides the New Query page of the online technical support application.

Listing 4-7 shows the content of the NewQuery.jsp file:

Listing 4-7: The NewQuery.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory, javax.xml.
transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException,javax.xml.transform.dom.
DOMSource,javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%
String temptitle, tempmessage, tempdate, tempuser, querypath;
/*Use request object to obtain query title, date, and query*/
temptitle=request.getParameter("txtfieldtitle");
tempmessage=request.getParameter("txtmessage");
tempdate=request.getParameter("txtdate");
/*Create a URL object to load the properties file*/
URL url=new URL("http://127.0.0.1:8080/fourth/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Obtain the querylist path value from path.properties file*/
Properties prop = new Properties();
prop.load(ucon.getInputStream());
querypath = prop.getProperty("querylistpath");
/*Check whether all fields are specified*/
if(!(temptitle == null || tempmessage == null ||tempdate == null))
{
/*Obtain a DocumentBuilder object by calling the newInstance() method*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the querylist XML document*/
Document doc = docb.parse(new FileInputStream(querypath));
/*Create a new query Element*/
Element doce = doc.getDocumentElement();
Element newe = doc.createElement("query");
/*Retrieve user ID attributes from session*/
tempuser=session.getAttribute("userid").toString();
/*Set title, msg, user, postedon attributes of query element*/
newe.setAttribute("title",temptitle);
newe.setAttribute("msg",tempmessage);
newe.setAttribute("user",tempuser);
newe.setAttribute("postedon",tempdate);
/*Create a new element received*/
Element rec = doc.createElement("received");
/*Set a msg attribute to received element*/
rec.setAttribute("msg","Thanks for your query. The administrator will address it promptly.");
/*Add received element to query element*/
newe.appendChild(rec);
/*Add Query element to root element*/
doce.appendChild(newe);
/*Call newInstance() of TransformerFactory class to obtain TransformerFactory object*/
TransformerFactory tFactory = TransformerFactory.newInstance();
/*Call newTransformer() method of TransformerFactory to obtain Transformer object*/
Transformer transformer = tFactory.newTransformer();
/*Set output property of Transformer object*/
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
/*Construct a DOMSource object as source of transformation*/
DOMSource source = new DOMSource(doc);
/*Create a StreamResult object to represent a stream to querylist XML document as result of transformation*/
StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(querypath)));
/*Perform the transformation*/
transformer.transform(source, result);%>
<center><% out.println("Query successfully submitted");%></center>
<%}
%>
<!--Page design to display fields to add new query-->
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online Technical Support
</em></strong></font></h2></td>
</tr>
</table>
<table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
<!--Display user ID retrieved from session object-->
<tr>
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#333333"><b>User </b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1"><div
align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
</table>
<p align="center">&nbsp;</p>
<p align="center"><font size="5"><b>New Query</b></font>
</p>
<div align="justify">
<!--Display Logout hyperlink-->
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 681px; top: 85px; width: 150" >
<tr>
<td height="18" bgcolor="#FFFFFF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<%
if ("admin".equals(session.getAttribute("userid")))
{
   /*For administrator, display hyperlink to AdminPage,jsp*/
   %>
   <tr>
   <td height="18" bgcolor="#FFFFFF"><div align="center"><b>
   <a href="AdminPage.jsp">
   Go to main page</a></b></div></td>
   </tr>
   <%
}
else
{
   /*For user, display hyperlink to UserPage,jsp*/
   %>
   <tr>
   <td height="18" bgcolor="#FFFFFF"><div align="center"><b>
   <a href="UserPage.jsp">
   Go to main page</a></b></div></td>
   </tr>
   <%
}%>
</table>
</div>
<!--Display form to add query. Submit data to same page-->
<form action = NewQuery.jsp method ="post">
<center>
<table width="409">
<!--Display Query Title text field-->
<tr>
<td width="165" bgcolor="#FFFFFF"><div align="center"><strong>Query
Title:</strong></div></td><td width="232" bgcolor="#FFFFFF">
<input name="txtfieldtitle" size="30">
</input></td>
</tr>
<!--Display Date text field-->
<tr>
<td width="165" bgcolor="#FFFFFF"><div
align="center"><strong>Date:</strong></div></td><td width="232"
bgcolor="#FFFFFF">
<input name="txtdate" ></td>
</tr>
<!--Display Query text area-->
<tr>
<td width="165" bgcolor="#FFFFFF"><div
align="center"><strong>Query:</strong></div></td><td width="232"
bgcolor="#FFFFFF"><textarea name="txtmessage" cols="30" rows="10"></textarea>
</td>
</tr><tr>
<td width="165"></input></td>
</tr>
</table>
<p>
<input type="submit" value="Submit Query">
</p>
</center>
</form>
End example

Download this listing.

The above code creates the New Query page of the online technical support application. The user interface of the New Query page contains the Query Title, Date, and Query fields. When an end user specifies query information and clicks the Submit button, the code uses the request object to retrieve that information. To add the query information to the querylist XML document, the code calls the parse() method of the DocumentBuilder object. The parse() method parses the XML document and creates an object tree of the document. The createElement() method of the code then creates an Element object, newe, which represents a query element in the XML document. Next, the setAttribute() method sets the title, msg, user, and postedon attributes for the Element object. The code creates another Element object, rec, which represents the receive element. The appendChild() method adds the rec element to the newe element and then the newe element to the root element. Finally, the code transforms the updated object tree to the XML document using the transform() method of the Transformer class.

Figure 4-4 shows the New Query page of the online technical support application:

Click To expand: This figure shows the New Query page that provides the Query Title, Date, and Query fields to accept query information from end users.
Figure 4-4: The New Query Page


Creating the Administrator Module

The administrator module of the online technical support application allows the administrator to post a reply to a query. The administrator module contains the AdminPage.jsp and QueryReply.jsp files that provide the Administrator Options and the Query Reply pages.

Creating the Administrator Options Page

The Administrator Options page contains hyperlinks an administrator can select to post a reply to a query and view other query replies. The AdminPage JSP provides the Administrator Options page of the application.

Listing 4-8 shows the content of the AdminPage.jsp file:

Listing 4-8: The AdminPage.jsp File
Start example
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Administrator Options</title>
</head>
<body>
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online Technical Support
</em></strong></font></h2></td>
</tr>
</table>
<p align="center"><b></b></p>
<table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<!--Display user ID from session-->
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#000000"><b>User </b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1">
<div align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
</table>
<div align="justify">
<!--Display hyperlink to DoLogout.jsp file-->
<table border="1" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 663px; top: 121px; width: 150">
<tr>
<td height="18" bgcolor="#FFFFFF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
</table>
</div>
<p align="center">&nbsp;</p>
<div align="justify">
<!--Display User Options table-->
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 262px; top: 255px; width: 300">
<tr>
<td bgcolor="#FFFFFF">
<p align="center"><b><font color="#FF0000">Administrator
Options</font></b></p>
</td>
</tr>
<!--Display hyperlink to ViewQueryList.jsp file-->
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="ViewQueryList.jsp">View query list</a></b></i></div></td>
</tr>
<!--Display hyperlink to QueryReply.jsp file-->
<tr>
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="QueryReply.jsp">Post  reply to query
</a></b></i></div></td>
</tr>
</table>
</div>
</body>
</html>
End example

Download this listing.

The above code creates the Administrator Options page of the online technical support application. The code displays the hyperlinks to the DoLogout.jsp, NewQuery.jsp, and QueryReply.jsp files.

Figure 4-5 shows the Administrator Options page of the online technical support application:

Click To expand: This figure shows the Administrator Options page that contains the Logout, View query list, and Post reply to query hyperlinks.
Figure 4-5: The Administrator Options Page

Creating the Query Reply Page

The Query Reply page allows the administrator to select a query and post a reply to it. This reply is added to the querylist.xml file. The QueryReply JSP provides the Query Reply page of the online technical support application.

Listing 4-9 shows the content of the QueryReply.jsp file:

Listing 4-9: The QueryReply.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory, javax.xml.
transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException, javax.xml.transform.dom.
DOMSource, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys, techdesk.*"%>
<%
String tempmsgTitle, tempdate,tempuser, tempmessage, querypath;
/*Use request object to obtain query title, query, and date*/
tempmsgTitle=request.getParameter("txtfieldmessage");
tempmessage=request.getParameter("txtmessage");
tempdate=request.getParameter("txtdate");
/*Create a URL object to load the properties file*/
URL url=new URL("http://127.0.0.1:8080/fourth/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Obtain the querylist path value from path.properties file*/
Properties prop = new Properties();
prop.load(ucon.getInputStream());
querypath = prop.getProperty("querylistpath");
/*Check whether all fields are specified*/
if(!(tempmsgTitle == null || tempmessage == null ||tempdate == null))
{
   /*Obtain a DocumentBuilder object by calling the newInstance() method*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the querylist XML document*/
   Document doc = docb.parse(new FileInputStream(querypath));
   /*Retrieve querylist root element*/
   NodeList nluserlist = doc.getElementsByTagName("querylist");
   /*Obtain a NodeList object that contains child elements of the root element*/
   Node doce = nluserlist.item(0);
   NodeList nl1 = doce.getChildNodes();
   /*Iterate through the NodeList object*/
   for(int int_1 = 0; int_1< nl1.getLength(); int_1 ++)
   {
      /*Obtain Node object by calling item() method of NodeList*/
      Node n = nl1.item(int_1);
      if((n.getNodeName()).equals("query"))
      {
         /*If node name is query, retrieve value of title attribute*/
         NamedNodeMap nnp= n.getAttributes();
         String temptitle2=(nnp.getNamedItem("title")).getNodeValue();
         /*Check retrieved value with value specified by end user*/
         if(tempmsgTitle.equals(temptitle2))
         {
            /*For matching title, create a reply element*/
            Element newe = doc.createElement("reply");
            /*Retrieve attribute from session*/
            tempuser=session.getAttribute("userid").toString();
            /*Check if this is a first reply*/
            if(temptitle2.startsWith("RE :"))
            {
               /*If reply already exist, set a msg attribute with two RE string preceding the reply*/
               newe.setAttribute("msg","RE : RE : " + tempmessage);
            }
            else
            {
                /*For first reply, set a msg attribute with a RE string preceding the reply*/
               newe.setAttribute("msg","RE : " + tempmessage);
            }
            /*Set user, and postedon attributes to reply element*/
            newe.setAttribute("user",tempuser);
            newe.setAttribute("postedon",tempdate);
            /*Add reply element to query element*/
            n.appendChild(newe);
         }
      }
   }
   /*Call newInstance() of TransformerFactory class to obtain TransformerFactory object*/
   TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Call newTransformer() method of TransformerFactory to obtain Transformer object*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Construct a DOMSource object as source of transformation*/
   DOMSource source = new DOMSource(doc);
   /*Create a StreamResult object to represent a stream to querylist XML document as result of transformation*/
   StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(querypath)));
   /*Perform the transformation*/
   transformer.transform(source, result);
}
%>
<!--Page design to display fields to add reply-->
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online Technical Support
</em></strong></font></h2></td>
</tr>
</table>
<table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
<!--Display user ID retrieved from session object-->
<tr>
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#000000"><b>User</b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1"><div
align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
</table>
<p align="center">&nbsp;</p>
<p align="center"><font size="5"><b>Query Reply </b></font>
</p>
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 695px; top: 86px; width: 150">
<!--Display Logout hyperlink-->
<tr>
<td height="18" bgcolor="#FFFFFF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<!--Display hyperlink to AdminPage.jsp-->
<tr>
<td height="18" bgcolor="#FFFFFF"><div align="center"><b>
<a href="AdminPage.jsp">
Go to main page</a></b></div></td>
</tr>
</table>
</div>
<!--Display form to add reply. Submit data to same page-->
<form action = QueryReply.jsp method ="post">
<center>
<table width="346">
<!--Display Query title drop-down list-->
<tr>
<td width="179" height="36" bgcolor="#FFFFFF"><div
align="center"><strong>Query title:</strong></div></td>
<td width="153" bgcolor="#FFFFFF">
<select name="txtfieldmessage">
<option value=""></option>
<%
/*Obtain a DocumentBuilder object by calling the newInstance() method*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the querylist XML document*/
Document doc = docb.parse(new FileInputStream(querypath));
/*Obtain a NodeList element that contains query elements as Node objects*/
NodeList nl1 = doc.getElementsByTagName("query");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1< nl1.getLength(); int_1 ++)
{
   /*Obtain the Node object that represent the XML query element*/
   Node n=nl1.item(int_1);
   /*Retrieve the NamedNodeMap object that contains attributes of query element*/
   NamedNodeMap nnp = n.getAttributes();
   %>
   <!--Populate drop-down list with value of the title attribute-->
   <option><%=(nnp.getNamedItem("title")).getNodeValue()%></option>
   <%
}
%>
</select></td>
</tr>
<!--Display the Date text field-->
<tr>
<td width="179" bgcolor="#FFFFFF"><div
align="center"><strong>Date:</strong></div></td><td width="153" bgcolor="#FFFFFF">
<input name="txtdate" ></td>
</tr>
<!--Display the Query text area-->
<tr>
<td width="179" bgcolor="#FFFFFF"><div
align="center"><strong>Query:</strong></div></td><td width="353" bgcolor="#FFFFFF">
<textarea name="txtmessage" cols="30" rows="5"></textarea></td>
</tr>
</table>
</center>
<tr>
<td width="179"><center><input type="submit" value="Post
Reply"></input></center></td>
</tr>
</table>
</form>
<!--Table to display existing queries-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 236px; top: 457px; width: 453px;">
<tr bgcolor="#FFFFFF">
<td colspan="2">
<p align="center"><i><font color="#FF0000"><b> Existing
Queries</b></font></i></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#FFFFFF"><div align="center"><font
color="#000000"><b>&nbsp; Title</b></font></div></td>
<td width="147" bgcolor="#FFFFFF"><div align="center"><font
color="#333333"><b> Content</b></font></div></td>
</tr>
<%
/*Obtain a DocumentBuilder object by calling the newInstance() method*/
docbfact = DocumentBuilderFactory.newInstance();
/*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
docb = docbfact.newDocumentBuilder();
/*Parse the querylist XML document*/
doc = docb.parse(new FileInputStream(querypath ));
/*Obtain a NodeList element that contains query elements as Node objects*/
nl1 = doc.getElementsByTagName("query");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain NamedNodeMap hat contains attributes of the query element*/
   Node n=nl1.item(int_1);
   NamedNodeMap nnp = n.getAttributes();
   %>
   <tr>
   <!--Display values of the title and msg attributes-->
   <td width="147" bgcolor="#FFFFFF"><div align="center"><%=
   (nnp.getNamedItem("title")).getNodeValue()%></div></td>
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("msg")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
</div>
End example

Download this listing.

The above code creates the Query Reply page of the online technical support application. The user interface displays the Query title, Date, and Reply fields. The code populates the Query title drop-down list with the values of the title attributes of the querylist XML document. When the administrator selects a query and posts a reply, the code calls the parse() method to parse the querylist XML document. The parse() method creates an object tree in the memory. The code compares the query title specified by the administrator with the values of the title attribute of the query elements. When a matching title is found, the code calls the createElement() method to create an Element object, newe, which represents a reply element. The setAttribute() method sets the msg attribute to the newe object. The appendChild() method adds the newe object to the Element object that represents the query element. Finally, the code transforms the object tree to the XML document by calling the transform() method of the Transformer object.

Figure 4-6 shows the Query Reply page of the online technical support application:

Click To expand: This figure shows the Query Reply page that displays the Query title, Date, and Reply fields.
Figure 4-6: The Query Reply Page


Creating the View Query Module

The view query module of the online technical support application allows end users to view queries and their replies in HTML and XML formats. This module also allows end users to download query information as XML files. Both the user and administrator modules provide access to the view query module. The view query module contains the ViewQueryList.jsp, ViewQuery.jsp, QueryXMLGenerator.class, and technicalhelpdesk.xsl files.

Creating the View Query Page

The View Query page of the online technical support application displays the fields in which an end user can select a query title and the output format to view the query and the replies. The View Query page also displays the existing queries stored in the querylist XML document. The ViewQueryList JSP provides the View Query page of the online technical support application.

Listing 4-10 shows the content of the ViewQueryList.jsp file:

Listing 4-10: The ViewQueryList.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer,javax.xml.transform.TransformerFactory, javax.xml.
transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException, javax.xml.transform.dom.
DOMSource, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys, techdesk.*"%>
<%! String result;%>
<%
String tempmsg,querypath;
tempmsg=request.getParameter("txtfieldmessage");
/*Create a URL object to load the properties file*/
URL url=new URL("http://127.0.0.1:8080/fourth/path.properties");
/*Open URL connection*/
URLConnection ucon=url.openConnection();
/*Obtain the querylistpath value and store in querypath variable*/
Properties prop = new Properties();
prop.load(ucon.getInputStream());
querypath = prop.getProperty("querylistpath");
%>
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online Technical Support
</em></strong></font></h2></td>
</tr>
</table>
<table border="1" width="215" cellspacing="0" cellpadding="0" height="1">
<!--Display user ID retrieved from session object-->
<tr>
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#333333"><b>User </b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1"><div
align="center"><%=session.getAttribute("userid")%></div></td>
</tr>
</table>
<p align="center">&nbsp;</p>
<p align="center"><font size="5"><b>View Query
</b></font></p>
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 689px; top: 85px; width: 150" >
<tr>
<td height="18" bgcolor="#FFFFFF"><div align="center"><font
color="#FFFFFF"><b><a
href="DoLogout.jsp">Logout</a></b></font></div></td>
</tr>
<%
if ("admin".equals(session.getAttribute("userid")))
{
   /*If user ID value retrieved from session is admin, display hyperlink to AdminPage.jsp*/
   %>
   <tr>
   <td height="18" bgcolor="#FFFFFF"><div align="center"><b>
   <a href="AdminPage.jsp">
   Go to main page</a></b></div></td>
   </tr>
   <%
}
else
{
   /*For all other users, display hyperlink to UserPage.jsp*/
   %>
   <tr>
   <td height="18" bgcolor="#FFFFFF"><div align="center"><b>
   <a href="UserPage.jsp">
   Go to main page</a></b></div></td>
   </tr>
   <%
}
%>
</table>
</div>
<!--Page design to display View Query page-->
<form action = "ViewQuery.jsp" method ="get" >
<center>
<table width="381">
<!--Display query title drop-down list-->
<tr>
<td width="122" bgcolor="#FFFFFF"><div align="center"><strong>Query
title:</strong></div></td><td width="50" bgcolor="#FFFFFF">
<select name="txtfieldmessage" >
<option value=""></option>
<%
/*Obtain a DocumentBuilder object by calling the newInstance() method*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the querylist XML document*/
Document doc = docb.parse(new FileInputStream(querypath));
/*Obtain a NodeList element that contains query elements as Node objects*/
NodeList nl1 = doc.getElementsByTagName("query");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
   {
      /*Obtain the Node object that represent the XML query element*/
      Node n=nl1.item(int_1);
      /*Retrieve the NamedNodeMap object that contains attributes of query element*/
      NamedNodeMap nnp = n.getAttributes();
      result=nnp.getNamedItem("title").getNodeValue();
      %>
      <!--Populate drop-down list with value of the title attribute-->
      <option >
      <%=result%>
      </option>
      <%
   }
%>
</select></td>
<!--Display Output drop-down list-->
<td width="193">
<strong>Output:</strong><select name="txtfieldxml" >
<option value = "yes"  >View query in XML</option>
<option value = "no"  >View query in HTML</option>
<option value = "dw"  >Download query</option>
</select>
</td>
</tr>
<tr>
<td width="122"></input></td>
</tr>
</table>
</center>
<p>
<center><input type="submit" value="View Query"></center>
</p>
</form>
<!--Display Existing Queries table-->
<div align="justify">
<table border="1" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 238px; top: 379px; width: 527px;">
<tr bgcolor="#FFFFFF">
<td colspan="2">
<p align="center"><i><font color="#FF0000"><b> Existing
Queries</b></font></i></p>
</td>
</tr>
<tr>
<td width="147" bgcolor="#FFFFFF"><div align="center"><font
color="#333333"><b> Title</b></font></div></td>
<td width="147" bgcolor="#FFFFFF"><div align="center"><font
color="#333333"><b>Content</b></font></div></td>
</tr>
<%
/*Obtain a DocumentBuilder object by calling the newInstance() method*/
docbfact = DocumentBuilderFactory.newInstance();
/*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
docb = docbfact.newDocumentBuilder();
/*Parse the querylist XML document*/
doc = docb.parse(new FileInputStream(querypath ));
/*Obtain a NodeList element that contains query elements as Node objects*/
nl1 = doc.getElementsByTagName("query");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
{
   /*Obtain NamedNodeMap hat contains attributes of the query element*/
   Node n=nl1.item(int_1);
   NamedNodeMap nnp = n.getAttributes();
   %>
   <tr>
   <!--Display values of the title and msg attributes-->
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("title")).getNodeValue()%></div></
   td>
   <td width="147" bgcolor="#FFFFFF"><div
   align="center"><%=(nnp.getNamedItem("msg")).getNodeValue()%></div></td>
   </tr>
   <%
}
%>
</table>
</div>
End example

Download this listing.

The above code creates the View Query page of the online technical support application. This code parses the querylist XML document and displays values of the title and msg attributes in tabular format. The user interface displays the Query title and Output drop-down lists. The code populates the Query title drop-down list with values of title attributes retrieved from the querylist XML document. The Output drop-down list contains the View query in XML, View query in HTML, and Download query options. When an end user selects a query title and output format, and clicks View Query, the code submits the data to the ViewQuery JSP page.

Figure 4-7 shows the View Query page of the online technical support application:

Click To expand: This figure shows the View Query page that displays the Query title and Output drop-down lists. The page also displays query information in the Existing Queries table.
Figure 4-7: The View Query Page

Creating the ViewQuery JSP Page

The ViewQuery JSP page dynamically displays XML content that contains query information in HTML and XML formats. This page also allows end users to download and save the XML content. Listing 4-11 shows the content of the ViewQuery.jsp file:

Listing 4-11: The ViewQuery.jsp File
Start example
<%@page import="techdesk.*"%>
<%@page contentType="application/xml"%>
<%
/*Use request object to view content of the query and the output type*/
String tempmsg,tempxml="no";
tempmsg=request.getParameter("txtfieldmessage");
tempxml=request.getParameter("txtfieldxml");
if (!("dw".equals(tempxml)))
{
   /*If user select either the XML Output or HTML Output to view query, specify XML version and
   /* encoding scheme*/
   out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
   if("no".equals(tempxml))
   {
      /*If user selects HTML Output to view query, use technicalhelpdesk.xsl stylesheet to render
      /* the HTML content*/
      out.println("<?xml-stylesheet type=\"text/xsl\"
      href=\"http://127.0.0.1:8080/fourth/xml/technicalhelpdesk.xsl\"?>");
   }
   /*Call getXML() method to dynamically generate the XML content and print out response*/
   out.println(QueryXMLGenerator.getXML(tempmsg));
}
else
  {
      /*If users selects the Download Content option, set the content-type response header as application/text*/
      response.setContentType("application/text");
      /*Set the Content-Disposition response header to indicate the file name of the file to
      ?* download as querycontent.xml*/
      response.setHeader("Content-Disposition","attachment;filename=querycontent.xml");
      /*Print out XML declaration*/
      out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      /*Call getXML() method to dynamically generate the XML content and print out response*/
      out.println(QueryXMLGenerator.getXML(tempmsg));
   }
%>
End example

Download this listing.

The above code creates the ViewQuery JSP page. The page directive specifies the content-type attribute value as application/xml to indicate that the JSP page will generate XML content. If an end user selects the View query in HTML or View query in XML option in the View Query page, the code prints the XML declaration. For the View query in HTML option, the code prints the style sheet reference that will create the HTML content. The code then calls the getXML() method of the QueryXMLGenerator class to generate and print the XML content. The code passes the query title specified by the end user as an argument to the getXML() method. If the end user selects the Download query option in the View Query page, the setContentType() method sets the content type of the response object as application/text. The setHeader() method sets the value of the header field Content-Disposition to attachment;filename=querycontent.xml. The header field value specifies to the browser that the content needs to be saved as querycontent.xml file. The code finally prints the XML declaration and String representation of the XML content returned by the getXML() method.

Creating the QueryXMLGenerator Class

The QueryXMLGenerator class generates the result of a query search in XML format. This class parses the querylist.xml file to generate the XML content as a String representation. Listing 4-12 shows the QueryXMLGenerator class of the online technical support application:

Listing 4-12: The QueryXMLGenerator Class
Start example
package techdesk;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import java.net.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
public class QueryXMLGenerator
{
   public static String getXML(String strMsgTitle) throws Exception
   {
     /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/fourth/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      /*Obtain the querylistpath value of the path.properties file*/
      String querypath = prop.getProperty("querylistpath");
      /*Create the String representation of the root element of querylist XML document*/
      String strTemp=new String();
      strTemp=strTemp+"<querylist>";
      /*Obtain a DocumentBuilder object by calling the newInstance() method*/
      DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
      /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
      DocumentBuilder docb = docbfact.newDocumentBuilder();
      /*Parse the querylist XML document*/
      Document doc = docb.parse(new FileInputStream(querypath));
      /*Obtain the root element*/
      NodeList nluserlist = doc.getElementsByTagName("querylist");
      /*Obtain the first child element of root element*/
      Node doce = nluserlist.item(0);
      /*Retrieve child nodes to retrieve NodeList object*/
      NodeList nl1 = doce.getChildNodes();
      /*Iterate through the NodeList object*/
      for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
      {
         Node n = nl1.item(int_1);
         if((n.getNodeName()).equals("query"))
         {
            /*For query element, get attributes as NamedNodeMap object*/
            NamedNodeMap nnp= n.getAttributes();
            /*Retrieve value of title attribute*/
            String tempmsg2=(nnp.getNamedItem("title")).getNodeValue();
            if(strMsgTitle.equals(tempmsg2))
            {
               /*Construct String representation of query element*/
               strTemp=strTemp+"\n<query msg=\""+(nnp.getNamedItem("msg")).getNodeValue()+"\"
               postedon=\""+(nnp.getNamedItem("postedon")).getNodeValue()+"\"
               title=\""+(nnp.getNamedItem("title")).getNodeValue()+"\"
               user=\""+(nnp.getNamedItem("user")).getNodeValue()+"\">";
               /*Retrieve sub element of query element as NodeList object*/
               NodeList nl2 = n.getChildNodes();
               /*Iterate through the NodeList object*/
               for(int int_2 = 0; int_2 < nl2.getLength(); int_2 ++)
               {
                  /*Retrieve the Node objects*/
                  Node n2=nl2.item(int_2);
                  if((n2.getNodeName()).equals("reply"))
                  {
                     /*For reply element, construct String representation of reply element*/
                     NamedNodeMap nnp1 = n2.getAttributes();
                     strTemp=strTemp+"\n<reply
                     msg=\""+(nnp1.getNamedItem("msg")).getNodeValue()+"\"
                     postedon=\""+(nnp1.getNamedItem("postedon")).getNodeValue()+"\"
                     user=\""+(nnp1.getNamedItem("user")).getNodeValue()+"\"/>";
                  }
               }
               /*Return String representation of XML document*/
               strTemp=strTemp+"\n</query>";
            }
         }
      }
      strTemp=strTemp+"\n</querylist>";
      return strTemp;
   }
}
End example

Download this listing.

The above code creates the QueryXMLGenerator class of the online technical support application. The getXML() method parses the querylist XML document to obtain the Document object. The getElementsByTagName("querylist") method returns a NodeList object that represents the root element of the XML document. The getChildNodes() method returns a NodeList object that provides access to the Node objects. Each Node object represents a query element of the XML document. The getAttributes() method of the Node object returns a NamedNodeMap object that provides access to the attributes of the XML document. The code compares the query title value that is passed as an argument to the getXML() method with the title attributes of the XML document. For matching titles, the code constructs XML content for the query element as a String object, strTemp. For query elements of the XML document that contain a reply subelement, the code constructs and adds XML content for the reply element to the String object, strTemp. Finally, the code returns the String object, strTemp, from the getXML() method.

Creating the technicalhelpdesk.xsl Style Sheet

The technicalhelpdesk.xsl style sheet provides the XML content generated by View Query JSP in HTML format.

Listing 4-13 shows the content of the technicalhelpdesk.xsl file:

Listing 4-13: The technicalhelpdesk.xsl File
Start example
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<head>
<title>Online Technical Support</title>
</head>
<body>
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online Technical Support
</em></strong></font></h2></td>
</tr>
</table>
<br/>
<center>
<a href="ViewQueryList.jsp">View query list</a>
</center>
<p align="center"><b><font size="5" color="#0000FF">Query
Results</font></b></p>
<div align="center">
<center>
<table border="1" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width="12%" align="center"><font
color="#800000"><b>User</b></font></td>
<td width="12%" align="center"><font
color="#800000"><b>Date</b></font></td>
<td width="20%" align="center"><font
color="#800000"><b>Title</b></font></td>
<td width="20%" align="center"><font
color="#800000"><b>Query</b></font></td>
<td width="35%" align="center">Reply</td>
</tr>
<xsl:for-each select="querylist">
<xsl:for-each select="query">
<tr>
<td width="12%"><xsl:value-of select="@user"/></td>
<td width="12%"><xsl:value-of select="@postedon"/> </td>
<td width="20%"><xsl:value-of select="@title"/> </td>
<td width="20%"><xsl:value-of select="@msg"/> </td>
<td width="35%">
<div align="left">
<xsl:for-each select="reply">
<table border="0" width="100%">
<tr>
<td width="33%"><xsl:value-of select="@postedon"/> </td>
<td width="33%"><xsl:value-of select="@user"/> </td>
<td width="34%"><xsl:value-of select="@msg"/> </td>
</tr>
</table>
</xsl:for-each>
</div>
</td>
</tr>
</xsl:for-each>
</xsl:for-each>
</table>
</center>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
End example

Download this listing.

The above code creates the technicalhelpdesk.xsl file. The <xsl:for-each select="query"> tag iterates through each query element of the XML content. For each query element, the <xsl:value-of> tag displays the content of the XML element. Each <xsl:value-of> tag contains a select attribute that specifies the XML attribute whose value needs to be displayed. The code also uses the <xsl:for-each > and <xsl:value-of> tags to display data of the reply element of the XML content.


Creating the Property File

The online technical support application uses a property file that stores the path to the XML files of the application. The following code shows the path.properties property file of the application:

userlistpath=c:/Chp4/code/xml/userlist.xml
querylistpath=c:/Chp4/code/xml/querylist.xml

The above code contains the following properties:

  • userlistpath: Stores the path to the userlist.xml file.

  • querylistpath: Stores the path to the querylist.xml file.

Note

The values of userlistpath and querylistpath are hard coded. Change the values to the complete path of the XML files stored in the computer.


Unit Testing

The online technical support application is deployed and tested on the Sun Java System Application Server Platform Edition 8. You can download this application server from:

http://java.sun.com/j2ee/1.4/download.html

Note

To install Sun Java System Application Server Platform Edition 8, you need to install Java 2 Standard Edition (J2SE) 1.4.2 on the computer.

To deploy the online technical support application:

  1. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Start Default Server from the Start menu to start the application server.

  2. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Deploytool from the Start menu to open the Deployment Tool window.

  3. Select New->Application from the File menu of the Deployment Tool window. The New Application dialog box appears.

  4. Click Browse in the New Application dialog box to display another New Application dialog box.

  5. Select the directory where you want to save the .ear file in the Look In combo box.

  6. Enter the name of the .ear file as OnlineTechnicalSupportApp in the File Name text box, as shown in Figure 4-8:

    Click To expand: This figure shows the New Application dialog box in which you can specify the name of the application file and the location to store it.
    Figure 4-8: The New Application Dialog Box

  7. Click the New Application button to return to the previous New Application dialog box.

  8. Click OK to create the new application.

  9. Select New->Web Component from the File menu of the Deployment Tool window. The New Web Application Wizard-Introduction dialog box appears.

  10. Click Next. The New Web Application Wizard-WAR File dialog box appears.

  11. Click Edit Contents in the New Web Application Wizard-WAR File dialog box. The Edit Contents of WebApp dialog box appears.

  12. Select all the JSP files, the QueryXMLGenerator.class file, and the path.properties file of the application from the Available Files pane and click Add. Select the xml directory as well from the Available Files pane and click Add. The Contents of WebApp pane of the Edit Contents of WebApp dialog box displays the added files, as shown in Figure 4-9:

    Click To expand: This figure shows the Edit Contents of WebApp dialog box that displays the files of the online technical support application.
    Figure 4-9: The Edit Contents of WebApp Dialog Box

  13. Click OK to add the files to the Web application Web Archive (WAR) file.

  14. Click Next in the New Web Application Wizard-WAR File dialog box. The New Web Application Wizard-Choose Component Type dialog box appears.

  15. Select the JSP Page radio button and click Next. The New Web Application Wizard-Component General Properties dialog box appears.

  16. Select Logon.jsp from the JSP Filename drop-down list. The remaining fields get automatically populated with values. Figure 4-10 shows the New Web Application Wizard-Component General Properties dialog box:

    Click To expand: This figure shows the New Web Application Wizard-Component General Properties dialog box in which you specify the main page of your application.
    Figure 4-10: The New Web Application Wizard-Component General Properties Dialog Box

  17. Click Finish.

  18. In the Deployment Tool window, specify/fourth as the context root of your application in the Context Root text field, as shown in Figure 4-11:

    Click To expand: This figure shows the Context Root text field of the Deployment Tool window in which you can specify the context root of the application.
    Figure 4-11: The Deployment Tool Window

  19. Select Save from the File menu of the Deployment Tool window to save the application.

  20. Select Deploy from the Tools menu. The Deploy Module OnlineTechnicalSupportApp dialog box appears.

  21. Specify the application server user name and password in the User Name and Password fields and click OK.

  22. The Distribute Module dialog box appears. It indicates the successful deployment of the application.

To test the deployed application:

  1. Specify the following URL in the address bar of the browser:

    http://localhost:8080/fourth/Logon.jsp

  2. In the Logon JSP page, specify Peter in the Logon ID field and peter in the Password field, as shown in Figure 4-12:

    Click To expand: This figure shows the User ID and Password fields of the Logon JSP page in which you need to specify values to log on to the application.
    Figure 4-12: The Logon JSP Page

  3. Click the Logon button. The DoLogon Page appears which displays the Logout and Go to main page hyperlinks.

  4. Select the Go to main page hyperlink. The User Options page appears, as shown in Figure 4-13:

    Click To expand: This figure shows the User Options page that displays the Post a new query and View query list hyperlinks.
    Figure 4-13: The User Options Page Containing Hyperlinks

  5. Select the Post a new query hyperlink. The New Query page appears.

  6. Specify a query to post, as shown in Figure 4-14:

    Click To expand: This figure shows the Query Title, Date, and Query fields of the New Query page in which you can post a new query.
    Figure 4-14: Posting a Query

  7. Click the Submit Query button to post the query.

  8. Check the querylist.xml file to ensure that your query has been added to the file.

  9. Select the Logout hyperlink in the New Query page. The Logon JSP page appears.

  10. Specify admin in the User ID and Password fields and click Logon. The Administrator Options page appears, as shown in Figure 4-15:

    Click To expand: This figure shows the Administrator Options page that displays the view query list and Post reply to query hyperlinks.
    Figure 4-15: The Administrator Options Page Containing Hyperlinks

  11. Select the Post reply to query hyperlink. The Query Reply page appears.

  12. Select the title of the query you posted using steps 5 through 7 from the Query title drop-down list. Specify the date of reply and the reply in the Date and Reply fields, as shown in Figure 4-16:

    Click To expand: This figure shows the Query Reply page in which you can post a reply to a query.
    Figure 4-16: Posting a Reply

  13. Click the Post Reply button.

  14. Check the querylist.xml file to ensure that the reply has been added to the file.

  15. Select the Go to main page hyperlink in the Query Reply page.

  16. Select the View query list hyperlink in the Administrator Options page. The View Query page appears.

  17. Select the title of the query you added in the user module from the Query title drop-down list. Select View query in XML from the Output drop-down list, as shown in Figure 4-17:

    Click To expand: This figure shows the View Query page in which you can select a query title and an output format to save query information.
    Figure 4-17: Selecting a Query Format

  18. Click the View Query button. The browser displays the dynamically generated XML content that contains the query information, as shown in Figure 4-18:

    Click To expand: This figure shows the dynamically generated XML content that contains the query you added and its reply.
    Figure 4-18: Dynamically Generated XML Content

  19. Click the Back button of the browser to return to the View Query page.

  20. In the View Query page, select View query in HTML from the Output drop-down list and click View Query.

  21. The style sheet of the application displays the XML content in HTML format, as shown in Figure 4-19:

    Click To expand: This figure shows the XML content provided by the style sheet in HTML format.
    Figure 4-19: Query in HTML Format

  22. In the View Query page, select Download query from the Output drop-down list and click View Query.

  23. The File Download dialog box appears, as shown in Figure 4-20:

    Click To expand: This figure shows the File Download dialog box that allows you to open or save the dynamically generated XML content.
    Figure 4-20: The File Download Dialog Box

  24. Click the Save button to save the content as an XML file. The Save As dialog box appears. From the Save in drop-down list, select the directory in which you want to save the XML file, as shown in Figure 4-21:

    Click To expand: This figure shows the Save As dialog box in which you can specify the directory to save the XML content as an XML file.
    Figure 4-21: The Save As Dialog Box

  25. Click Save to save the content as an XML file.

  26. Select Logout in the View Query page to logout from the application.


Point 5: Developing JSP Custom Tags for Integrating and Displaying XML Data

JSP custom tags are user-defined tags that follow XML syntax to perform repetitive tasks in JSP pages. For example, instead of parsing an XML document in multiple JSP pages, you can develop and use a custom tag in JSP pages to parse XML documents. You can also use custom tags in JSP pages to parse and display data stored in XML documents. A JSP custom tag allows you to separate the presentation and business logic requirements of a JSP application. You can develop custom tags to display user interfaces and handle business logic, such as reading and writing to XML documents. You can also include custom tags in JSP pages to make the pages smaller, simpler, and well-structured as compared to JSP pages without tags.

To develop a custom tag, you need to create a tag handler class. A tag handler class is a Java class that implements the functioning of the custom tag. You also need to create a Tag Library Descriptor (TLD) file for the custom tag. TLD is an XML document that describes the custom tag. You can then include the custom tag in a JSP page using the JSP taglib directive.

This chapter describes how to create an online article processing application that stores application data in XML files. The JSP pages of this application use custom tags to access, add, and manipulate content stored in XML files. The JSP pages also use custom tags to develop user interfaces to format and display XML content.

Architecture of the Online Article Processing Application

The online article processing application allows an end user to view and rate articles posted on the Web. The administrator of the application can post, update, and delete articles.

The application stores information about end users and articles in XML files. The JSP pages of the application use custom tags to parse XML documents and create object trees of the XML documents in the memory. In addition, the JSP pages use custom tags to transform the object tree back to the XML document. The XML files of the application are:

  • articlelist.xml: Stores information about articles, such as category, article ID, and rating.

  • userlist.xml: Stores information about end users, such as user ID, password, and role. There are two types of end user roles, user and administrator.

The JSP files of the application are:

  • LoginPage.jsp: Displays the text and password fields that allow the end user to log on.

  • DoLogon.jsp: Authenticates an end user and displays user interfaces that correspond to the end user role.

  • AdminPage: Provides a user interface that allows an end user with administrator role to add and search articles.

  • UserPage: Provides a user interface that allows an end user with user role to search articles.

  • ShowArticleRatings.jsp: Displays ratings for articles.

  • DoAddArticle: Provides the user interface to add articles.

  • DoSearchArticles.jsp: Displays search results and the fields to update, delete, and rate articles.

  • ModifyDeleteRate.jsp: Acts as a controller and dispatches user request to the DoUpdateArticle.jsp, DoDeleteArticle.jsp, or DoRateArticle.jsp files to update, delete, or rate an article.

  • DoUpdateArticle.jsp: Updates information about an article.

  • DoDeleteArticle.jsp: Deletes information about an article.

  • DoRateArticle.jsp: Records ratings for articles.

To add, update, or delete articles, the JSP pages use custom tags. The custom tags also help JSP pages display banner and copyright information in the user interfaces of the application. The tag handlers for the custom tags of the article processing application are:

  • ShowLoginTag.java: Displays the login form of the application.

  • ShowHeaderTag.java: Displays the application banner.

  • ShowFooterTag.java: Displays copyright information.

  • ShowArticleTag.java: Displays article information.

  • ShowArticleRatingsTag.java: Displays ratings for articles.

  • FrmSearchTag.java: Displays a form to search for an article.

  • FormAddArticleTag.java: Displays a form to add an article.

  • DoLoginTag.java: Parses the userlist.xml file to authenticate end user information.

  • DoAddArticleTag.java: Parses and transforms the articlelist.xml file to add article information.

  • DoUpdateArticleTag.java: Parses and transforms the articlelist.xml file to update article information.

  • DoDeleteArticleTag.java: Parses and transforms the articlelist.xml file to delete article information.

  • DoRateArticleTag.java: Parses and transforms the articlelist.xml file to record article ratings.

Figure 5-1 shows the architecture of the online article processing application:

Click To expand: This figure shows the JSP files the online article processing application uses and the sequence in which it uses them.
Figure 5-1: Architecture of the Online Article Processing Application


Creating XML Files

The article processing application stores information about end users and articles in the userlist.xml and articlelist.xml files. The userlist.xml file stores information, such as user ID, password, and role, as shown in Listing 5-1:

Listing 5-1: The userlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<userlist>
<user name="user1" password="puser1">
<role name="administrator"/>
</user>
<user name="user2" password="puser2">
<role name="user"/>
</user>
<user name="user3" password="puser3">
<role name="user"/>
</user>
</userlist>
End example

Download this listing.

The above code uses the userlist root element that encloses user elements. A user element contains the name and password attributes. Each user element encloses a role element. The name attribute of the role element represents an end user role.

The articlelist.xml file stores information about articles, such as article ID, category, content, and rating, as shown in Listing 5-2:

Listing 5-2: The articlelist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<articlelist>
<article articleid="PN001" category="j2ee">
<detail text="J2EE Containers:&#13;&#10;The J2EE server provides underlying services
to components using containers. Examples of J2EE containers are, Application Client Container,
Applet Container, Web Container, and EJB Container.&#13;&#10;">
<rating rating="7" userid="user2"/>
</detail>
</article>
</articlelist>
End example

Download this listing.

The above code uses the articlelist root element that encloses article elements. An article element contains the article ID and category attributes. This element encloses the detail and rating elements. The detail element contains the content of the article. The rating element contains the rating attributes that specify the article rating and the userid attribute that specifies the user ID of the end user who rated the article.


Creating the TLD File

The TLD file of the online article processing application is an XML-based file that defines the custom tags of the application. The TLD file uses the taglib root element to enclose the tag elements. Each tag element of the TLD file defines a custom tag. The TLD file of the online article processing application is technicaldocs-taglib.tld, as shown in Listing 5-3:

Listing 5-3: The technicaldocs-taglib.tld File
Start example
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>techdoc</shortname>
<info>
A tag library for Online Technical Processing Application
</info>
<!--TAG TO DISPLAY HEADING AND SUBHEADING-->
<tag>
<name>header</name>
<tagclass>technicaldocs.ShowHeaderTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>subheading</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<!--TAG TO DISPLAY FOOTER-->
<tag>
<name>footer</name>
<tagclass>technicaldocs.ShowFooterTag</tagclass>
<bodycontent>EMPTY</bodycontent>
</tag>
<!--TAG TO DISPLAY LOGIN FORM-->
<tag>
<name>formlogin</name>
<tagclass>technicaldocs.ShowLoginTag</tagclass>
<bodycontent>EMPTY</bodycontent>
</tag>
<!--TAG TO DO LOGIN-->
<tag>
<name>dologin</name>
<tagclass>technicaldocs.DoLoginTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>userid</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>password</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<!--TAG TO DISPLAY SEARCH FORM-->
<tag>
<name>formsearcharticle</name>
<tagclass>technicaldocs.FrmSearchTag</tagclass>
<bodycontent>EMPTY</bodycontent>
</tag>
<!--TAG TO DISPLAY ARTICLE ADDITION FORM-->
<tag>
<name>formaddarticle</name>
<tagclass>technicaldocs.FormAddArticleTag</tagclass>
<bodycontent>EMPTY</bodycontent>
</tag>
<!--TAG TO ADD ARTICLE -->
<tag>
<name>doaddarticle</name>
<tagclass>technicaldocs.DoAddArticleTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>category</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>articleid</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>article</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<!-- TAG TO DELETE ARTICLE -->
<tag>
<name>dodeletearticle</name>
<tagclass>technicaldocs.DoDeleteArticleTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>category</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>articleid</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<!--TAG TO MODIFY ARTICLE-->
<tag>
<name>doupdatearticle</name>
<tagclass>technicaldocs.DoUpdateArticleTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>category</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>articleid</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>article</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<!--TAG TO RATE ARTICLE-->
<tag>
<name>doratearticle</name>
<tagclass>technicaldocs.DoRateArticleTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>category</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>articleid</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>userid</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>rating</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<!--TAG TO SHOW ARTICLE Rating-->
<tag>
<name>showarticleratings</name>
<tagclass>technicaldocs.ShowArticleRatingsTag</tagclass>
<bodycontent>EMPTY</bodycontent>
</tag>
<!--TAG TO DISPLAY ARTICLE-->
<tag>
<name>showarticle</name>
<tagclass>technicaldocs.ShowArticleTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>category</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>articleid</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>article</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
End example

Download this listing.

The above code creates the TLD file of the online article processing application. The taglib root element of the TLD file uses the tlibversion and jspversion elements to specify the tag library and JSP version. A tag element of the TLD file uses the name and tagclass elements to specify the name and the tag handler class of the custom tag. The bodycontent element specifies whether the custom tag is empty or contains body contents. For custom tags that have attributes, the tag element contains attribute elements that allow you to specify the attribute values. Each attribute element represents an attribute of a tag and contains the name, required, and rtexprvalue elements. The name element specifies the attribute name and the required element specifies whether the attribute is mandatory. The rtexprvalue element specifies whether the tag supports regular expressions.


Creating the Logon Module

The Logon module of the application provides a user interface that helps authenticate an end user. The Logon module contains the LoginPage.jsp and DoLogin.jsp files. The LoginPage.jsp file uses the custom tags implemented by the ShowHeaderTag, ShowFooterTag, and ShowLoginTag tag handlers. The DoLogin.jsp file uses the custom tag implemented by the DoLoginTag tag handler.

Creating the Logon Page

The Logon Page of the online article processing application uses a custom tag to display the user ID and password fields. This page also displays the banner and copyright information of the application using custom tags. The LoginPage.jsp file provides the Logon page of the application, as shown in Listing 5-4:

Listing 5-4: The LoginPage.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc"%>
<html>
<body>
<!--Use header custom tag to display banner-->
<techdoc:header subheading="Logon Page"/>
<br><br>
<table width=100%>
<td>
<!--Use formlogin custom tag to display Login form-->
<techdoc:formlogin/>
</td>
</table>
<br><br><br><br>
<!--Use footer custom tag to display copyright information-->
<techdoc:footer/>
</body>
</html>
End example

Download this listing.

The above code uses the taglib directive to include the reference to the TLD file of the application in the JSP page. The <techdoc:header subheading="Logon Page"/> custom tag displays the banner of the application. The <techdoc:formlogin/> and <techdoc:footer/> custom tags display the logon form and the copyright information of the application.

Figure 5-2 shows the Logon Page of the application:

Click To expand: This figure shows the Logon Page of the application that displays the Logon ID and Password fields and a Logon button.
Figure 5-2: The Logon Page

Creating the Logon Handler

The logon handler of the application uses a custom tag to authenticate an end user. The logon handler passes the user ID and password as attributes to the custom tag. The DoLogin JSP page is the logon handler of the application. Listing 5-5 shows the content of the DoLogin.jsp file:

Listing 5-5: The DoLogin.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc"%>
<html>
<body>
<!--use header custom tag to display banner-->
<techdoc:header subheading=""/>
<Br><Br>
<tr>
<td>
<table width=100%>
<td>
<%
/*Retrieve user information from request object*/
String tempuserid = request.getParameter("userid");
String temppassword = request.getParameter("password");
%>
<Center>
<!--Use dologin tag to authenticate logon information-->
<techdoc:dologin userid="<%=tempuserid%>" password="<%=temppassword%>"/>
</Center>
</td>
</table>
<Br><Br>
<!--Use footer custom tag to display copyright information-->
<techdoc:footer/>
</body>
</html>
End example

Download this listing.

The above code creates the logon handler of the application. The <techdoc:header /> and <techdoc:footer /> custom tags display the banner and copyright information. The code uses the request implicit object to obtain an end user-specified user ID and password. The <techdoc:dologin /> custom tag accepts the user ID and password values of an end user for authentication.

Creating the ShowHeaderTag Tag Handler

The JSP pages of the application use the <techdoc:header/> custom tag to display the banner. The ShowHeaderTag.java file is the tag handler of the <techdoc:header/> custom tag, as shown in Listing 5-6:

Listing 5-6: The ShowHeaderTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class ShowHeaderTag extends TagSupport
{
   /*Declare sub heading attribute*/
   private String subheading="";
   /*Declare ge and set methods for attributes*/
   public String getSubheading()
   {
      return subheading;
   }
   public void setSubheading(String String_1)
   {
      subheading=String_1;
   }
   public int doStartTag()
   {
     try {
            /*Obtain JSPWriter object to print out response*/
            JspWriter out = pageContext.getOut();
            out.print("<table bgcolor=\"#0099FF\" height=\"10%\" width=\"100%\">");
            out.print("<tr>");
            out.print("<td>");
            /*Display banner title*/
            out.print("<p align=\"center\"><h2 align=\"center\"><font
            color=\"#FFFFFF\"
            size=\"5\"><strong><em>Articles
            Online</em></strong></font></h2>");
            /*Display tag attribute*/
            out.print("<p align=\"center\"><b><font color=\"#FFFFFF\"
            size=\"3\">"+getSubheading()+"</font></b></p>");
            out.print("</tr>");
            out.print("</td>");
            out.print("</table>");
          } catch(IOException ioe)
         {
            System.out.println("Error in HeaderTag: " + ioe);
         }
         return(SKIP_BODY);
     }
}
End example

Download this listing.

The above code creates the ShowHeaderTag tag handler. The code declares the subheading attribute of the custom tag as a private field and defines accessor and mutator methods for the attribute. The doStart() method displays the banner and calls the getSubheading() method to display the attribute value in the banner.

Creating the ShowFooterTag Tag Handler

The user interface of the online article processing application displays copyright information using the <techdoc:footer /> custom tag. The ShowFooterTag tag handler implements the <techdoc:footer /> custom tag, as shown in Listing 5-7:

Listing 5-7: The ShowFooterTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class ShowFooterTag extends TagSupport
{
   public int doStartTag()
    {
      try {
            JspWriter out = pageContext.getOut();
            out.print("<table bgcolor=\"#0099FF\" height=\"5%\" width=\"100%\">");
            out.print("<tr>");
            out.print("<td>");
            out.print("<p align=\"left\"><font color=\"#FFFFFF\"
            size=\"5\"><b>Copy Right
            (c), ETechArticles Inc. 2004</b></font></p>");
            out.print("</tr>");
            out.print("</td>");
            out.print("</table>");
           } catch(IOException ioe)
           {
              System.out.println("Error in FooterTag: " + ioe);
           }
           return(SKIP_BODY);
      }
   }
End example

Download this listing.

The above code prints the copyright information in the doStartTag() method. The code returns the SKIP_BODY constant from the doStartTag() method to indicate that the JSP engine should not evaluate the body of the tag.

Creating the ShowLoginTag Tag Handler

The Logon Page of the online article processing application uses the <techdoc:formlogin/> custom tag to display the logon form. The ShowLoginTag tag handler implements the <techdoc:formlogin/> custom tag and displays the fields to accept logon information. Listing 5-8 shows the content of the ShowLoginTag.java file:

Listing 5-8: The ShowloginTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class ShowLoginTag extends TagSupport
{
   public int doStartTag()
   {
      try {
            /*Obtain JspWriter object*/
            JspWriter out = pageContext.getOut();
            /*Create HTML Form and submit data to DoLogin.jsp*/
            out.println("<form method=\"get\" action=\"DoLogin.jsp\">");
            out.println("<table border=\"1\" width=\"81%\" cellpadding=\"0\"
            cellspacing=\"0\" border=\"0\">");
            out.println("<tr>");
            /*Display text field to accept Logon ID*/
            out.println("<td width=\"28%\" bgcolor=\"#FFFFFF\"
            colspan=\"2\"><b><font size=\"3\"
            color=\"##333333\"><Center>Logon
            ID:</Center></font></b></td>");
            out.println("<td width=\"28%\" bgcolor=\"#FFFFFF\" colspan=\"2\"><input
            name=\"userid\"/></td>");
            out.println("</tr>");
            /*Display password field to accept Password*/
            out.println("<tr>");
            out.println("<td width=\"28%\" bgcolor=\"#FFFFFF\"
            colspan=\"2\"><b><font size=\"3\"color=\"##333333\
            "><Center>Password:</Center></font></b></td>");
            out.println("<td width=\"28%\" bgcolor=\"#FFFFFF\" colspan=\"2\"><input
            type =\"password\" name=\"password\"/></td>");
            out.println("</tr>");
            out.println("</table>");
            out.println("<center><input type=\"submit\" value=\"Logon\" name=\"login\"
            \"><input type=\"reset\" value=\"Reset\" \"></center>");
            out.println("<td width=\"1%\">&nbsp;</td>");
            out.println("</tr>");
            out.println("</form>");
         }
         catch(IOException ioe)
         {
            System.out.println("Error in HeaderTag: " + ioe);
         }
         return(SKIP_BODY);
      }
}
End example

Download this listing.

The above code creates the ShowLoginTag tag handler. The code creates the userID and Password fields and a Logon button in the doStartTag() method. The doStartTag() method returns the SKIP_BODY constant to indicate that the JSP engine should not evaluate the body of the tag.

Creating the DoLoginTag Tag Handler

The DoLoginTag tag handler implements the <techdoc:dologin/> custom tag. This tag handler accesses the userlist.xml file to authenticate the logon information specified by the end user. Listing 5-9 shows the code for the DoLoginTag.java file:

Listing 5-9: The DoLoginTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
import javax.servlet.http.*;
import java.util.*;
import java.net.*;
public class DoLoginTag extends TagSupport
{
  /*Declare tag attributes*/
   private String userid;
   private String password;
  /*Declare setXXX() methods of attributes*/
   public void setUserid(String String_1)
   {
      userid = String_1;
   }
   public void setPassword(String String_1)
   {
      password = String_1;
   }
   /*Declare getXXX() methods of attributes*/
   public String getUserid()
   {
      return userid;
   }
   public String getPassword()
   {
      return password;
   }
   public int doStartTag()
   {
      try
      {
         /*Create a URL object to load the properties file*/
         URL url=new URL("http://127.0.0.1:8080/fifth/path.properties");
         /*Open URL connection*/
         URLConnection ucon=url.openConnection();
         /*Retrieve the userlistpath property*/
         Properties prop = new Properties();
         prop.load(ucon.getInputStream());
         String userpath = prop.getProperty("userlistpath");
         /*Obtain HttpSession object*/
         JspWriter out = pageContext.getOut();
         HttpSession session = pageContext.getSession();
         /*Create object of DocumentBuilder factory, using newInstance() method of DocumentBuilderFactory*/
         DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
         /*Create object of DocumentBuilder using the newDocumentBuilder() method of DocumentBuilderFactory */
         DocumentBuilder docb = docbfact.newDocumentBuilder();
         /*Parse the XML document*/
         Document doc = docb.parse(new FileInputStream(userpath));
         /*Obtain a NodeList object that represents the elements of the XML file with name user*/
         NodeList nl1 = doc.getElementsByTagName("user");
         /*Iterate through the NodeList object*/
         for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
         {
            /*Retrieve NamedNodeMap object*/
            Node n=nl1.item(int_1);
            NamedNodeMap nnp = n.getAttributes();
            /*Check user name and password retrieved with the values specified by end user*/
            if((nnp.getNamedItem("name").getNodeValue()).equals(getUserid())&&
            (nnp.getNamedItem("password").getNodeValue()).equals(getPassword()))
            {
               /*Retrieve child node of user node*/
               NodeList nl2 = n.getChildNodes();
               Node n2=nl2.item(1);
               /*Retrieve attribute of child node*/
               NamedNodeMap nnp1 = n2.getAttributes();
               /*retrieve attribute value of child node*/
               String temprole = (nnp1.getNamedItem("name")).getNodeValue();
               /*store user id and role name retrieved as attribute value in session*/
               session.setAttribute("userid", getUserid());
               session.setAttribute("role", temprole);
               if(temprole.equals("administrator"))
               {
                  /*For administrator role, display hyperlink to AdminPage.jsp*/
                  out.println("<a href=\"AdminPage.jsp\"> Administrator main page
                  </a>");
               }
               else
               {
                /*For user role, display hyperlink to UserPage.jsp*/
               out.println("<a href=\"UserPage.jsp\"> User main page</a>");
               }
            }
         }
      } catch(IOException ioe)
      {
         System.out.println("Error in DoLoginTag: " + ioe);
      }
      catch(Exception oe)
      {
         System.out.println("Error in DoLoginTag: " + oe);
      }
      return(SKIP_BODY);
   }
}
End example

Download this listing.

The above code creates the DoLoginTag tag handler. The userid and password private fields represent attributes of the <techdoc:dologin/> custom tag. The accessor and mutator methods allow you to access the tag attributes and set the attribute values. In the doStartTag() method, the code uses the DocumentBuilder object and calls the parse() method to parse the userlist.xml file. The parse() method returns the DocumentBuilder object, which represents an object tree of the userlist document in the memory. The code iterates through the nodes of the object tree to authenticate logon information.


Creating the Administer Article Page

An end user of the online article processing application with administrator role can add and search articles in the Administer Article page. The AdminPage JSP creates the Administer Article page, as shown in Listing 5-10:

Listing 5-10: The AdminPage.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc" %>
<html>
<body>
<!--Use header custom tag to display banner-->
<techdoc:header subheading="Administer Article"/>
<tr>
<td>
<p align="center"><a href="ArticleRatings.jsp">View article
ratings</a></p>
<table width=100%>
<td>
<!--Use formaddarticle custom tag to display form to add article-->
<techdoc:formaddarticle/>
</td>
<td>
<!--Use formsearcharticle custom tag to display form to search article-->
<techdoc:formsearcharticle/>
</td>
</table>
<br>
<!--Display hyperlink to login page-->
<center><a href="LoginPage.jsp">Logout</a></center>
<br>
<!--Use footer custom tag to display copyright information-->
<techdoc:footer/>
</body>
</html>
End example

Download this listing.

The above code creates the Administer Article page. The <techdoc:formaddarticle/> and <techdoc:formsearcharticle/> custom tags display the forms to add and search for articles. The code also displays a View Article Ratings hyperlink, which allows you to access the ArticleRatings.jsp file.

Figure 5-3 shows the Administer Article page of the online article processing application:

Click To expand: This figure shows the Administer Article page that displays the forms to add and search for articles.
Figure 5-3: The Administer Article Page


Creating the User Page

The User Page uses a custom tag to display the fields that allow an end user to select a category and specify keywords to search for articles. The UserPage JSP provides the User Page of the online article processing application, as shown in Listing 5-11:

Listing 5-11: The UserPage.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc"%>
<html>
<body>
<!--Use header custom tag to display banner-->
<techdoc:header subheading="User Page"/>
<tr>
<td>
<table width=100%>
<td>
<p align="center"><a href="ArticleRatings.jsp">View Article Ratings</a></p>
<center>
<!--Use formsearcharticle custom tag to display form to search article-->
<techdoc:formsearcharticle/>
</center>
</td>
</table>
<br>
<center><a href="LoginPage.jsp">Logout</a></center>
<br>
<!--Use footer custom tag to display copyright information-->
<techdoc:footer/>
</body>
</html>
End example

Download this listing.

The above code creates the User Page of the online article processing application. The <techdoc:formsearcharticle/> custom tag displays the form in which end users can specify information to search for articles. The code also displays the View Article Ratings hyperlink, which allows you to access the ArticleRatings.jsp file.

Figure 5-4 shows the User Page of the online article processing application:

Click To expand: This figure shows the User Page of the online article processing application. It contains a Category drop-down list and a Keyword text field in which an end user can specify information to search for articles.
Figure 5-4: The User Page


Creating the Files to Search for Articles

All end users can search for articles by specifying the category and keyword criteria. The files of the application that allow an end user to search for articles are:

  • FrmSearchTag.java: Implements the <techdoc:formsearcharticle/>custom tag that displays the form to search for articles.

  • DoSearchArticle.jsp: Parses the articlelist.xml file to retrieve articles and uses the <techdoc:showarticle/>custom tag to display articles.

  • ShowArticleTag.java: Implements the <techdoc:showarticle/> custom tag to display search results.

Creating the FrmSearchTag Tag Handler

The FrmSearchTag tag handler implements the <techdoc:formsearcharticle /> custom tag. This tag handler displays the fields in which an end user can specify the search criteria.

Listing 5-12 shows the content of the FrmSearchTag.java file:

Listing 5-12: The FrmSearchTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class FrmSearchTag extends TagSupport
{
   public int doStartTag()
   {
      try {
            /*Retrieve JSPWriter object to print out response*/
            JspWriter out = pageContext.getOut();
            /*Create HTML form that submits information to DoSearchArticle.jsp*/
            out.println("<form method=\"get\" action=\"DoSearchArticle.jsp\">");
            out.println("<table border=\"1\" width=\"46%\" cellpadding=\"0\"
            cellspacing=\"0\">");
            out.println("<tr>");
            out.println("<td width=\"100%\" colspan=\"2\" bgcolor=\"#FF00FF\">");
            out.println("<p align=\"center\"><b>SEARCH
            ARTICLE</b></td>");
            out.println("</tr>");
            /*Display drop-down list to select category*/
            out.println("<tr>");
            out.println("<td width=\"45%\" bgcolor=\"#808080\"><b><font
            size=\"3\"
            color=\"#00FFFF\">Category</font></b></td>");
            out.println(" <td width=\"55%\" bgcolor=\"#808080\"><select size=\"1\"
            name=\"category\">");
            out.println("<option value=\"corejava\">CORE JAVA</option>");
            out.println("<option value=\"j2ee\">J2EE</option>");
            out.println("<option value=\"vc++\">VC++</option>");
            out.println("</select></td>");
            out.println("</tr>");
            out.println("<tr>");
            /*Display field to specify keyword*/
            out.println("<td width=\"45%\" bgcolor=\"#808080\"><b><font
            size=\"3\"
            color=\"#00FFFF\">Keyword</font></b></td>");
            out.println("<td width=\"55%\" bgcolor=\"#808080\"><input type=\"text\"
            name=\"keyword\" size=\"15\"></td>");
            out.println("</tr>");
            out.println("<tr>");
            /*Display Submit and Reset button*/
            out.println("<td width=\"45%\"><input type=\"submit\" value=\"Submit\"
            name=\"B1\"></td>");
            out.println("<td width=\"55%\"><input type=\"reset\" value=\"Reset\"
            name=\"B2\"></td>");
            out.println("</tr>");
            out.println("</table>");
            out.println("</form>");
         }
         catch(IOException ioe)
         {
            System.out.println("Error in HeaderTag: " + ioe);
         }
         return(SKIP_BODY);
     }
}
End example

Download this listing.

The above code creates the FrmSearchTag tag handler. This code displays the Category drop-down list and the Keyword text field. The code uses the Submit button to submit the search information to the DoSearchArticle.jsp file.

Creating the DoSearchArticle JSP Page

The DoSearchArticle JSP page accesses the articlelist.xml file to retrieve information about articles, based on the search criteria specified by the end user. The JSP page uses the <techdoc:showarticle/> custom tag to display the retrieved information.

Listing 5-13 shows the content of the DoSearchArticle.jsp file:

Listing 5-13: The DoSearchArticle.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.util.*, java.net.*, java.io.*, org.w3c.dom.*"%>
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc" %>
<html>
<head>
<title>Article Search Result Page</title>
</head>
<body>
<%!String articlepath;%>
<%
String temprole=(String)session.getAttribute("role");
if("administrator".equals(temprole) || "user".equals(temprole))
{
   %>
   <%String tempsubheading="View Article";%>
   <!--use header custom tag to display banner-->
   <techdoc:header subheading="<%=tempsubheading%>"/>
   <%
   /*Retrieve category and keyword for article to retrieve*/
   String tempcategory =request.getParameter("category");
   String tempkeyword=request.getParameter("keyword");
   /*Check whether category and keyword are specified*/
   if(!(tempcategory==null || tempcategory ==null ))
   {
      try
      {
         /*Create a URL object to load the properties file*/
         URL url=new URL("http://127.0.0.1:8080/fifth/path.properties");
         /*Open URL connection*/
         URLConnection ucon=url.openConnection();
         /*Retrieve the articlelistpath property*/
         Properties prop = new Properties();
         prop.load(ucon.getInputStream());
         articlepath = prop.getProperty("articlelistpath");
      }
      catch(Exception ex)
      {
         ex.printStackTrace();
      }
      /*Create a DocumentBuilderFactory object*/
      DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
      /*Call newDocumentBuilder to create a DocumentBuilder object*/
      DocumentBuilder docb = docbfact.newDocumentBuilder();
      /*Parse the XML document*/
      Document doc = docb.parse(new FileInputStream(articlepath));
      %>
      <div align="justify">
      <table border="1" cellpadding="0" cellspacing="0" width="100%" >
      <tr>
      <td colspan="2" bgcolor="#008080">
      <p align="center"><i><font color="#FFFFFF"><b>Article Search
      Result</b></font></i></p>
      </td>
      </tr>
      <%
      /*Obtain a NodeList object that represents the elements of the XML file with name user*/
      NodeList nl1 = doc.getElementsByTagName("article");
      /*Iterate through the NodeList object*/
      for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
      {
         Node n=nl1.item(int_1); NamedNodeMap nnp = n.getAttributes();
         if((nnp.getNamedItem("category").getNodeValue()).equals(tempcategory))
         {
            /*Retrieve NamedNodeMap corresponding to article ID attribute*/
            String temparticleid=(nnp.getNamedItem("articleid")).getNodeValue();
            NodeList nl2 = n.getChildNodes();
            Node n2=nl2.item(1);
            NamedNodeMap nnp1 = n2.getAttributes();
            /*Retrieve article content*/
            String temparticle=(nnp1.getNamedItem("text").getNodeValue()).toUpperCase();
            if(temparticle.indexOf(tempkeyword.toUpperCase(),0)!=-1)
            {%>
               <tr>
               <td>
               <!--use showarticle custom tag to display banner-->
               <techdoc:showarticle category="<%=tempcategory%>"
               articleid="<%=temparticleid%>" article="<%=temparticle%>"/>
               </td>
               </tr>
               <%
            }
         }
      }
      %>
      </table>
      </div>
      <%
   }
   else
   {%>
      Please enter something in the Keyword field.
      <%
   }%>
   <p align="center">&nbsp;</p>
   <%
   if(temprole.equals("administrator"))
   {
      %>
      <p align="center"><a href="AdminPage.jsp">Back to administration
      page</a></p>
      <%
   }
   %>
   <%
   if(temprole.equals("user"))
   {
      %>
      <p align="center"><a href="UserPage.jsp">Back to user page</a></p>
      <%
   }
}
%>
<techdoc:footer/>
</body>
</html>
End example

Download this listing.

The above code uses the request object to retrieve the category and keyword an end user specifies to search for articles. The parse() method of the DocumentBuilder object parses the articlelist.xml file. The parse() method returns a Document object that represents an object tree of the articlelist document. The code iterates through the nodes of the object tree to retrieve article information that matches the specified search criteria. If an article matches the search criteria, the code uses the <techdoc:showarticle/> custom tag to display that article. The code passes the category, article ID, and article content as attributes of the <techdoc:showarticle/> custom tag.

Creating the ShowArticleTag Tag Handler

The ShowArticleTag tag handler implements the <techdoc:showarticle/> custom tag to display article information. The tag handler obtains information about articles that are passed as tag attributes. This information is displayed in tabular format. The tag handler also displays the Update, Delete, and Rate buttons to update, delete, and rate articles. Listing 5-14 shows the content of the ShowArticleTag.java file:

Listing 5-14: The ShowArticleTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import javax.servlet.http.*;
import java.io.*;
public class ShowArticleTag extends TagSupport
   {
      /*Declare tag attributes*/
      private String category="";
      private String articleid="";
      private String article="";
      /*Declare setXXX() methods for attributes*/
      public void setCategory(String String_1)
      {
         category=String_1;
      }
      public void setarticleid(String String_1)
      {
         articleid=String_1;
      }
      public void setArticle(String String_1)
      {
         article=String_1;
      }
      /*Declare getXXX() methods for attributes*/
      public String getCategory()
      {
         return category;
      }
      public String getArticleid()
      {
         return articleid;
      }
      public String getArticle()
      {
         return article;
      }
      public int doStartTag()
      {
         try
         {
            /*Obtain JspWriter object*/
            JspWriter out = pageContext.getOut();
            /*Retrieve HttpSession object*/
            HttpSession session = pageContext.getSession();
            /*Retrieve role from session*/
            String temprole = (String)session.getAttribute("role");
            /*Create form and submit to ModifyDeleteRate.jsp*/
            out.println("<form method=\"get\" action=\"ModifyDeleteRate.jsp\">");
            out.println("<input type=\"hidden\" name=\"task\" />");
            out.println("<table border=\"1\" width=\"81%\" cellpadding=\"0\"
            cellspacing=\"0\">");
            out.println("<tr>");
            out.println("<td width=\"28%\" bgcolor=\"#808080\"
            colspan=\"2\"><b><font size=\"3\"
            color=\"#00FFFF\">Category</font></b></td>");
            out.println("<input type=\"hidden\" name=\"category\"
            value=\""+getCategory()+"\"/>");
            out.println("<td width=\"72%\" bgcolor=\"#808080\"
            colspan=\"2\">"+getCategory()+"</td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td width=\"28%\" bgcolor=\"#808080\"
            colspan=\"2\"><b><font size=\"3\" color=\"#00FFFF\">Article");
            out.println("ID</font></b></td>");
            out.println("<input type=\"hidden\" name=\"articleid\"
            value=\""+getArticleid()+"\"/>");
            out.println("<td width=\"72%\" bgcolor=\"#808080\"
            colspan=\"2\">"+getArticleid()+"</td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td width=\"28%\" bgcolor=\"#808080\"
            colspan=\"2\"><b><font size=\"3\"
            color=\"#00FFFF\">Article</font></b></td>");
            out.println("<td width=\"72%\" bgcolor=\"#808080\" colspan=\"2\"><textarea
            rows=\"2\" name=\"article\"
            cols=\"36\">"+getArticle()+"</textarea></td>");
            out.println("</tr>");
            out.println("<tr>");
            if(temprole.equals("administrator"))
            {
               out.println("<td width=\"61%\"><input type=\"button\" value=\"Modify\"
               name=\"Modify\"
               onClick=\"{this.form.task.value='modify';this.form.submit();}\"></td>");
               out.println("<td width=\"62%\" colspan=\"2\"><input type=\"button\"
               value=\"Delete\" name=\"delete\"
               onClick=\"{this.form.task.value='delete';this.form.submit();}\"></td>");
               out.println("<td width=\"1%\">&nbsp;</td>");
            }
            else if(temprole.equals("user"))
            {
               out.println("<td width=\"61%\">Rating (1 - 10)<input type=\"text\"
               name=\"rating\" /></td>");
               out.println("<td width=\"61%\"><input type=\"button\" value=\"Rate\"
               name=\"Rate\"
               onClick=\"{this.form.task.value='rate';this.form.submit();}\"></td>");
            }
            out.println("</tr>");
            out.println("</table>");
            out.println("</form>");
            }
            catch(IOException ioe)
            {
               System.out.println("Error in HeaderTag: " + ioe);
               return(SKIP_BODY);
            }
            return(SKIP_BODY);
   }
}
End example

Download this listing.

The above code creates the ShowArticleTag tag handler. The category, articleid, and article private fields represent the attributes of the <techdoc:showarticle/> custom tag. The values of the category, articleid, and article private fields can be retrieved and set using accessor and mutator methods. The code also contains the doStartTag() method, which calls the accessor methods to retrieve values that are passed as attributes to the <techdoc:showarticle/> custom tag. The code uses the attribute values to retrieve and print article information. Next, the code obtains the value of an end user role stored in the session object. For end users with administrator role, the code displays the Update and Delete buttons for each article to update or delete an article. When the administrator clicks the Update or Delete button, a request parameter task is sent along with the request to the ModifyDeleteRate JSP page. For end users with user role, the code displays the Rate button.

Figure 5-5 shows the View Articles page of the online article processing application that displays articles to end users with administrator role:

Click To expand: This figure shows the View Articles Page that displays articles and the Update and Delete buttons for end users with administrator role.
Figure 5-5: The View Articles Page for Administrator Role

Figure 5-6 shows the View Articles page of the online article processing application that displays articles to end users with user role:

Click To expand: This figure shows the View Articles Page that displays articles and a Rate button for end users with user role.
Figure 5-6: The View Articles Page for User Role


Creating the Files to Add Articles

An administrator of the online article processing application can add new articles using the Administer Article page. Information about new articles is stored in the arliclelist.xml file. The files that enable an administrator to add articles are:

  • FormAddArticleTag.java: Implements the <techdoc:formaddarticle /> custom tag. The Administer Article page of the online article processing application uses the <techdoc:formaddarticle /> custom tag.

  • DoAddArticle.jsp: Uses the <techdoc:doaddarticle/> custom tag to add articles.

  • DoAddArticleTag.java: Implements the <techdoc:doaddarticle/> custom tag. The DoAddArticleTag tag handler parses the articlelist.xml file and adds information about new articles in the XML document.

Creating the FormAddArticleTag Tag Handler

The FormAddArticleTag tag handler implements the <techdoc:formaddarticle /> custom tag. The tag handler displays the fields that enable an administrator to specify information about new articles. The tag handler submits this information to the DoAddArticle JSP page. Listing 5-15 shows the FormAddArticleTag.java file:

Listing 5-15: The FormAddArticleTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class FormAddArticleTag extends TagSupport
{
   public int doStartTag()
   {
      try
      {
        /*Retrieve JSPWriter object to print out response*/
        JspWriter out = pageContext.getOut();
        /*Create HTML form that posts content to DoAddArticle.jsp*/
        out.println("<form method=\"Post\" action=\"DoAddArticle.jsp\">");
        out.println("<table border=\"1\" width=\"75%\" cellpadding=\"0\"
        cellspacing=\"0\">");
        out.println("<tr>");
        out.println("<td width=\"100%\" colspan=\"2\" bgcolor=\"#FF00FF\">");
        out.println("<p align=\"center\"><b>ADD
        ARTICLE</b></td>");
        out.println("</tr>");
        /*Display drop-down list to select category*/
        out.println("<tr>");
        out.println("<td width=\"36%\" bgcolor=\"#808080\"><b><font
        size=\"3\" color=\"#00FFFF\">Category</font></b></td>");
        out.println("<td width=\"64%\" bgcolor=\"#808080\"><select size=\"1\"
        name=\"category\">");
        out.println("<option value=\"corejava\">CORE JAVA</option>");
        out.println("<option value=\"j2ee\">J2EE</option>");
        out.println("<option value=\"vc++\">VC++</option>");
        out.println("</select></td>");
        out.println("</tr>");
        /*Display fields to add article info*/
        out.println("<tr>");
        out.println("<td width=\"36%\" bgcolor=\"#808080\"><b><font
        size=\"3\" color=\"#00FFFF\">Article");
        out.println("ID</font></b></td>");
        out.println("<td width=\"64%\" bgcolor=\"#808080\"><input
        type=\"text\" name=\"articleid\"size=\"25\"></td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td width=\"36%\" bgcolor=\"#808080\"><b><font
        size=\"3\" color=\"#00FFFF\">Article</font></b></td>");
        out.println("<td width=\"64%\" bgcolor=\"#808080\"><textarea
        rows=\"20\" name=\"article\" cols=\"36\"></textarea></td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td width=\"36%\"><input type=\"submit\" value=\"Submit\"
        name=\"B1\"></td>");
        out.println("<td width=\"64%\"><input type=\"reset\" value=\"Reset\"
        name=\"B2\"></td>");
        out.println("</tr>");
        out.println("lt;/table>");
        out.println("</form>");
     }
      catch(IOException ioe)
      {
         System.out.println("Error in FormAddArticleTag: " + ioe);
      }
      return(SKIP_BODY);
   }
}
End example

Download this listing.

The above code creates the FormAddArticleTag tag handler of the online article processing application. The Category drop-down list displays the categories of articles. End users can select a category and specify the article ID and content of the new article in the Article ID text field and Article text area. When an end user clicks the Submit button after specifying the article ID and content, the code submits the information to the DoAddArticle JSP page.

Creating the DoAddArticle JSP Page

The DoAddArticle JSP page uses the <techdoc:doaddarticle/> custom tag to add information about new articles, as shown in Listing 5-16:

Listing 5-16: The DoAddArticle.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc" %>
<html>
<head>
<title>Article Addition Result Form</title>
</head>
<body>
<%
/*Retrieve user role from session*/
String temprole=(String)session.getAttribute("role");
/*Check if user role is administrator*/
if("administrator".equals(temprole) )
{
   %>
   <!--For administrator role, use header custom tag to display banner-->
   <techdoc:header subheading="Add Article Result"/>
   <%
   /*Retrieve article information from request object*/
   String tempcategory =request.getParameter("category");
   String temparticleid=request.getParameter("articleid");
   String temparticle=request.getParameter("article");
   /*Check whether all article information is specified*/
   if(!(tempcategory==null || temparticleid ==null || temparticle == null))
   {
      %>
      <Center>
      <!--Use doaddarticle tag to add article-->
      <techdoc:doaddarticle category="<%=tempcategory%>"
      articleid="<%=temparticleid%>" article="<%=temparticle%>"/></Center>
      <%
   }
   else
   {
      %>
      Please enter values for all three items in the form.
      <%
   }
   %>
   <p align="center">&nbsp;</p>
   <!--Display hyperlink to administrator page-->
   <p align="center"><a href="AdminPage.jsp">Back to administration
   page</a></p>
   <!--Use footer custom tag to display copyright information-->
   <techdoc:footer/>
   <%
}
%>
</body>
</html>
End example

Download this listing.

The above code uses the HttpRequest object to retrieve information about a new article from the category, articleid, and article request parameters. The code passes this information as attributes to the <techdoc:doaddarticle/> tag. This tag adds the new information to the articlelist.xml file.

Creating the DoAddArticleTag Tag Handler

The DoAddArticleTag tag handler implements the <techdoc:doaddarticle/> tag. The attribute values of the <techdoc:doaddarticle/> tag provide information to the tag handler about the new articles you want to add to the articlelist.xml file. The tag handler uses DOM to add the information to the articlelist.xml file.

Listing 5-17 shows the content of the DoAddArticleTag.java file:

Listing 5-17: The DoAddArticleTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
import java.util.*;
import java.net.*;
public class DoAddArticleTag extends TagSupport
{
  /*Declare the tag attributes*/
   private String category="";
   private String articleid="";
   private String article="";
  /*Define setXXX() methods for tag attributes*/
   public void setCategory(String String_1)
   {
      category=String_1;
   }
   public void setarticleid(String String_1)
   {
      articleid=String_1;
   }
   public void setArticle(String String_1)
   {
      article=String_1;
   }
        /*Definr getXXX() methods for tag attributes*/
   public String getCategory()
   {
      return category;
   }
   public String getArticleid()
   {
      return articleid;
   }
   public String getArticle()
   {
      return article;
   }
   public int doStartTag()
   {
     try
      {
         /*Create a URL object to load the properties file*/
         URL url=new URL("http://127.0.0.1:8080/fifth/path.properties");
         /*Open URL connection*/
         URLConnection ucon=url.openConnection();
         /*Retrieve the articlelistpath property*/
         Properties prop = new Properties();
         prop.load(ucon.getInputStream());
         String articlepath = prop.getProperty("articlelistpath");
         /*Create object of DocumentBuildeFactory, using newInstance() method of
         DocumentBuilderFactory */
         DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
         /*Create object of DocumentBuilder using the newDocumentBuilder() method of
         DocumentBuilderFactory */
         DocumentBuilder docb = docbfact.newDocumentBuilder();
         /*Parse the articlelist.xml document and obtain a Document object*/
         Document doc = docb.parse(new FileInputStream(articlepath));
         /*Obtain Element object that represents root element of XML document*/
         Element doce = doc.getDocumentElement();
         /*Create a new element, article*/
         Element newe = doc.createElement("article");
         /*Set category and article ID attributes for the article element*/
         newe.setAttribute("category",getCategory());
         newe.setAttribute("articleid",getArticleid());
         /*Create a detail element*/
         Element newe1 = doc.createElement("detail");
         /*Set text attribute for the detail element*/
         newe1.setAttribute("text",getArticle());
         /*Append detail element to article element*/
         newe.appendChild(newe1);
         /*Append article element to root element*/
         doce.appendChild(newe);
         /*Create a TransformerFactory by calling the newInstance() method of
         TransformerFactory class*/
         TransformerFactory tFactory = TransformerFactory.newInstance();
         /*Obtain a Transformer object by calling the newTransformer() method of
         TransformerFactory class*/
         Transformer transformer = tFactory.newTransformer();
         /*Set output property of Transformer object*/
         transformer.setOutputProperty(OutputKeys.INDENT,"yes");
         /*Specify the source of the transformation*/
         DOMSource source = new DOMSource(doc);
         /*Create the StreamResult holder for  transformation to the articlelist.xml file*/
         StreamResult result = new StreamResult(new PrintStream(new
         FileOutputStream(articlepath)));
         /*Perform the transformation*/
         transformer.transform(source, result);
         /*Print out success message*/
         JspWriter out = pageContext.getOut();
         out.print("The article has been successfully added.");
      }
      catch(IOException ioe)
      {
         System.out.println("Error in HeaderTag: " + ioe);
      }
      catch(Exception oe)
      {
         System.out.println("Error in HeaderTag: " + oe);
      }
      return(SKIP_BODY);
   }
}
End example

Download this listing.

The category, articleid, and article fields of the above code represent the attributes of the <techdoc:doaddarticle/> tag. The accessor and mutator methods allow access to the article ID and article fields. In the doStartTag() method, the tag handler parses the articlelist.xml file using the parse() method of the DocumentBuilder object. The parse() method returns a Document object that represents an object tree of the XML document. The code uses the Document object to create a new Element object in the object tree that corresponds to the new article. The code sets the attributes of the Element object with the value of its fields. Finally, the code transforms the object tree to the articlelist XML document using the transform() method of the Transformer object.


Creating the Files to Update Articles

The files that allow an administrator to update articles are:

  • ModifyDeleteRate.jsp: Forwards update requests to the DoUpdateArticle.jsp file.

  • DoUpdateArticle.jsp: Uses the <techdoc:doupdatearticle/> custom tag to update information about articles.

  • DoUpdateArticleTag.java: Implements the <techdoc:doupdatearticle/> custom tag to update information about articles stored in the articlelist.xml file.

Creating the ModifyDeleteRate JSP Page

The ModifyDeleteRate JSP page acts as a controller to send requests to other JSP pages. When an administrator clicks Update or Delete in the View Articles page, the ModifyDeleteRate JSP page receives the request, checks its type, and forwards it to the corresponding JSP page.

Listing 5-18 shows the content of the ModifyDeleteRate.jsp file:

Listing 5-18: The ModifyDeleteRate.jsp File
Start example
<%
/*Retrieve task to perform. ask can be updating, deleting, and rating article*/
String temptask = request.getParameter("task");
if("modify".equals(temptask))
    {
      /*For updating, forward request to  DoUpdateArticle.jsp*/ %>
      <jsp:forward page="DoUpdateArticle.jsp"/>
      <%
     }
    if("delete".equals(temptask))
     {
         /*For deleting, forward request to  DoDeletArticle.jsp*/
         %>
         <jsp:forward page="DoDeleteArticle.jsp"/>
         <%
     }
     if("rate".equals(temptask))
     {
         /*For rating, forward request to  DoRateArticle.jsp*/
         %>
         <jsp:forward page="DoRateArticle.jsp"/>
         <%
      }
      %>
End example

Download this listing.

The above code uses the HttpRequest object to obtain the value of the request parameter, task. This parameter contains a modify or delete value, depending on the Update or Delete button an administrator clicks in the DoSearchArticle JSP page. For the modify, delete, or rate values of the task parameter, the code forwards the request to the DoUpdateArticle.jsp, DoDeleteArticle.jsp, and DoRateArticle.jsp files.

Creating the DoUpdateArticle JSP Page

The DoUpdateArticle JSP page uses the <techdoc:doupdatearticle/> custom tag to update articles. The JSP page retrieves information to update an article from the HttpRequest object. The page passes this information to the tag handler as values of the attributes of the <techdoc:doupdatearticle/> custom tag. Listing 5-19 shows the content of the DoUpdateArticle.jsp file:

Listing 5-19: The DoUpdateArticle.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc" %>
<html>
<head>
<title>Article Addition Result Form</title>
</head>
<body>
<%
/*Retrieve user role from session*/
String temprole=(String)session.getAttribute("role");
/*Check if user role is administrator*/
if("administrator".equals(temprole) )
  {
      %>
      <!--For administrator role, use header custom tag to display banner-->
      <techdoc:header subheading=" "/>
      <%
      /*Retrieve article information from request object*/
      String tempcategory =request.getParameter("category");
      String temparticleid=request.getParameter("articleid");
      String temparticle=request.getParameter("article");
      /*Check whether all article information is specified*/
      if(!(tempcategory==null || temparticleid ==null ||temparticle == null))
      {
         %>
         <!--Use doupdatearticle tag to add article-->
         <techdoc:doupdatearticle category="<%=tempcategory%>"
         articleid="<%=temparticleid%>" article="<%=temparticle%>"/>
         <%
      }
      %>
      <p align="center">&nbsp;</p>
      <!--Display hyperlink to administrator page-->
      <p align="center"><a href="AdminPage.jsp">Back to Administrator
      Page</a></p>
      <!--Use footer custom tag to display copyright information-->
      <techdoc:footer/>
      <%
   }
   %>
   </body>
   </html>
End example

Download this listing.

The above code uses the HttpRequest object to obtain the values of the category, articleid, and article parameters. The code specifies the values of the parameters as attributes of the <techdoc:doupdatearticle/> custom tag.

Creating the DoUpdateArticleTag Tag Handler

The DoUpdateArticleTag tag handler implements the <techdoc:doupdatearticle/> custom tag. The tag handler updates the content of the articlelist.xml file with the values of the attributes passed to the <techdoc:doupdatearticle/> custom tag.

Listing 5-20 shows the content of the DoUpdateArticleTag.java file:

Listing 5-20: The DoUpdateArticleTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
import java.util.*;
import java.net.*;
public class DoUpdateArticleTag extends TagSupport
     {
         /*Declare tag attributes*/
         private String category="";
         private String articleid="";
         private String article="";
         /*Define setXXX() methods for tag attributes*/
         public void setCategory(String String_1)
         {
            category=String_1;
         }
         public void setArticleid(String String_1)
         {
            articleid=String_1;
         }
         public void setArticle(String String_1)
         {
            article=String_1;
         }
         /*Define getXXX() methods for tag attributes*/
         public String getCategory()
         {
            return category;
         }
         public String getArticleid()
         {
            return articleid;
         }
         public String getArticle()
         {
            return article;
         }
         public int doStartTag()
         {
         try
            {
            /*Create a URL object to load the properties file*/
            URL url=new URL("http://127.0.0.1:8080/fifth/path.properties");
            /*Open URL connection*/
            URLConnection ucon=url.openConnection();
            /*Retrieve the articlelistpath property*/
            Properties prop = new Properties();
            prop.load(ucon.getInputStream());
            String articlepath = prop.getProperty("articlelistpath");
            /*Create object of DocumentBuildeFactory, using newInstance() method of
            DocumentBuilderFactory */
            DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
            /*Create object of DocumentBuilder using the newDocumentBuilder() method of
            DocumentBuilderFactory */
            DocumentBuilder docb = docbfact.newDocumentBuilder();
            /*Parse the articlelist.xml document and obtain a Document object*/
            Document doc = docb.parse(new FileInputStream(articlepath));
            /*Obtain a NodeList object that represents the elements of the XML file with name
            articlelist*/
            NodeList nluserlist = doc.getElementsByTagName("articlelist");
            /*Obtain the Node object by calling the item() method of NodeList*/
            Node doce = nluserlist.item(0);
            NodeList nl1 = doce.getChildNodes();
            /*Iterate through the NodeList object*/
            for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
            {
               Node n = nl1.item(int_1);
               if((n.getNodeName()).equals("article"))
               {
                  /*Obtain the NamedNodeMap object that represents the attributes of the article
                  element*/
                  NamedNodeMap nnp= n.getAttributes();
                  /*Get values for the category and article ID attributes*/
                  String tempcategory=(nnp.getNamedItem("category")).getNodeValue();
                  String temparticleid=(nnp.getNamedItem("articleid")).getNodeValue();
                  /*Check retrieved values with end user specified values*/
                  if((getCategory()).equals(tempcategory) &&
                  (getArticleid()).equals(temparticleid))
                  {
                     /*Retrieve the child node*/
                     NodeList nl2 = n.getChildNodes();
                     Node articlenode = nl2.item(1);
                     /*remove the child node*/
                     n.removeChild(articlenode);
                     /*Create a new element detail*/
                     Element newElement = doc.createElement("detail");
                     /*Create a text attribute with article contents*/
                     newElement.setAttribute("text",getArticle());
                     /*Append the text node to article node*/
                     n.appendChild(newElement);
                  }
               }
            }
           /*Create a TransformerFactory by calling the newInstance() method of
           TransformerFactory
           class*/
           TransformerFactory tFactory = TransformerFactory.newInstance();
           /*Obtain a Transformer object by calling the newTransformer() method of
           TransformerFactory
           class*/
           Transformer transformer = tFactory.newTransformer();
           /*Set output property of Transformer object*/
           transformer.setOutputProperty(OutputKeys.INDENT,"yes");
           /*Specify the source of the transformation*/
           DOMSource source = new DOMSource(doc);
           /*Create the StreamResult holder for  transformation to the articlelist.xml file*/
           StreamResult result = new StreamResult(new PrintStream(new
           FileOutputStream(articlepath)));
           /*Perform the transformation*/
           transformer.transform(source, result);
           /*Print out successful message*/
           JspWriter out = pageContext.getOut();
           out.print("The article has been successfully updated.");
        }
         catch(IOException ioe)
         {
            System.out.println("Error in HeaderTag: " + ioe);
         }
         catch(Exception oe)
         {
            System.out.println("Error in HeaderTag: " + oe);
         }
         return(SKIP_BODY);
      }
   }
End example

Download this listing.

The category, articleid, and article fields of the above code represent the attributes of the <techdoc:doupdatearticle/> custom tag. The accessor and mutator methods retrieve and set the field values. The parse() method parses the articlelist.xml file and creates an object tree of the XML document. The code locates the node in the object tree that corresponds to the article to be updated. The removeChild() method removes the node that represents the content of the article you want to update. The code then creates a new node using the createElement() method of the Document object. The setAttribute() method of the Element object adds the updated content of the article to the node. Finally, the code transforms the object tree back to the articlelist XML document using the transform() method of the Transformer object.


Creating the Files to Delete Articles

The files that allow an administrator to delete articles using the View Articles page are:

  • DoDeleteArticle.jsp: Uses the <techdoc:dodeletearticle/> custom tag to delete articles.

  • DoDeleteArticleTag.java: Implements the <techdoc:dodeletearticle/> custom tag.

Creating the DoDeleteArticle JSP Page

The DoDeleteArticle JSP page uses the <techdoc:dodeletearticle/> custom tag to delete articles. When you select an article for deletion, the JSP page retrieves its category and article ID from the HttpRequest object. The page passes this information to the tag handler using the attributes of the tag. Listing 5-21 shows the content of the DoDeleteArticle.jsp file:

Listing 5-21: The DoDeleteArticle.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc" %>
<html>
<head>
<title>Article Addition Result Form</title>
</head>
<body>
<%
String temprole=(String)session.getAttribute("role");
if("administrator".equals(temprole) || "user".equals(temprole))
   {
      %>
      <!--Use header custom tag to display banner-->
      <techdoc:header subheading=" "/>
      <%
      /*Retrieve article category and article ID to delete*/
      String tempcategory =request.getParameter("category");
      String temparticleid=request.getParameter("articleid");
      if(!(tempcategory==null || temparticleid ==null))
      {
         %>
         <!--Use doadeletearticle tag to deletearticle-->
         <techdoc:dodeletearticle category="<%=tempcategory%>"
         articleid="<%=temparticleid%>"/>
         <%
       }
     %>
      <p align="center">&nbsp;</p>
      <p align="center"><a href="AdminPage.jsp">Back to administrator
      page</a></p>
      <!--Use footer custom tag to display copyright information-->
      <techdoc:footer/>
      <%
  }
   %>
   </body>
   </html>
End example

Download this listing.

The above code uses the HttpRequest object to obtain the values of the category and articleid parameters. The code specifies the values of the parameters as attributes of the <techdoc:dodeletearticle/> custom tag.

Creating the DoDeleteArticleTag Tag Handler

The DoDeleteArticleTag tag handler implements the <techdoc:dodeletearticle/> custom tag. The tag handler deletes information about articles from the articlelist.xml file that correspond to the category and article ID specified as attribute values of the custom tag.

Listing 5-22 shows the content of the DoDeleteArticleTag.java file:

Listing 5-22: The DoDeleteArticleTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
import java.util.*;
import java.net.*;
public class DoDeleteArticleTag extends TagSupport
    {
      /*Declare the tag attributes*/
      private String category="";
      private String articleid="";
      private String article="";
      /*Define setXXX() methods for tag attributes*/
      public void setCategory(String String_1)
      {
         category=String_1;
      }
      public void setArticleid(String String_1)
      {
         articleid=String_1;
      }
      /*Definr getXXX() methods for tag attributes*/
      public String getCategory()
      {
         return category;
      }
      public String getArticleid()
      {
         return articleid;
      }
      public int doStartTag()
      {
         try
         {
            /*Create a URL object to load the properties file*/
            URL url=new URL("http://127.0.0.1:8080/fifth/path.properties");
            /*Open URL connection*/
            URLConnection ucon=url.openConnection();
            /*Retrieve the articlelistpath property*/
            Properties prop = new Properties();
            prop.load(ucon.getInputStream());
            String articlepath = prop.getProperty("articlelistpath");
            /*Create object of DocumentBuildeFactory, using newInstance() method of
            DocumentBuilderFactory */
            DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
            /*Create object of DocumentBuilder using the newDocumentBuilder() method of
            DocumentBuilderFactory */
            DocumentBuilder docb = docbfact.newDocumentBuilder();
            /*Parse the articlelist.xml document and obtain a Document object*/
            Document doc = docb.parse(new FileInputStream(articlepath));
            /*retrieve NodeList object corresponding to articlelist element*/
            NodeList nluserlist = doc.getElementsByTagName("articlelist");
            /*Retrieve NodeList for child elements*/
            Node doce = nluserlist.item(0);
            NodeList nl1 = doce.getChildNodes();
            /*Iterate through the NodeList object*/
            for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
            {
               /*Check for the article element*/
               Node n = nl1.item(int_1);
               if((n.getNodeName()).equals("article"))
               {
                  /*Retrieve value of category and article ID attributes for the article
                  element*/
                  NamedNodeMap nnp= n.getAttributes();
                  String tempcategory=(nnp.getNamedItem("category")).getNodeValue();
                  String temparticleid=(nnp.getNamedItem("articleid")).getNodeValue();
                  /*Check retrieved value with end user specified value to delete*/
                  if((getCategory()).equals(tempcategory) &&
                  (getArticleid()).equals(temparticleid))
                  {
                     /*Delete element from XML file*/
                     doce.removeChild(n);
                  }
                }
           }
          /*Create a TransformerFactory by calling the newInstance() method of
          TransformerFactory class*/
         TransformerFactory tFactory = TransformerFactory.newInstance();
         /*Obtain a Transformer object by calling the newTransformer() method of
         TransformerFactory class*/
         Transformer transformer = tFactory.newTransformer();
         /*Set output property of Transformer object*/
         transformer.setOutputProperty(OutputKeys.INDENT,"yes");
         /*Specify the source of the transformation*/
         DOMSource source = new DOMSource(doc);
         /*Create the StreamResult holder for  transformation to the articlelist.xml file*/
         StreamResult result = new StreamResult(new PrintStream(new
         FileOutputStream(articlepath)));
         /*Perform the transformation*/
         transformer.transform(source, result);
         /*Print out success message*/
         JspWriter out = pageContext.getOut();
         out.print("<center>The article has been successfully deleted.</center>");
        }
        catch(IOException ioe)
        {
            System.out.println("Error in HeaderTag: " + ioe);
        }
         catch(Exception oe)
         {
             System.out.println("Error in HeaderTag: " + oe);
         }
         return(SKIP_BODY);
       }
   }
End example

Download this listing.

The above code creates the DoDeleteArticleTag tag handler of the online article processing application. The category and articleid fields represent the attributes of the <techdoc:dodeletearticle/> custom tag. The accessor and mutator methods of the code retrieve and set the field values. In the doStartTag() method, the code parses the articlelist.xml file and creates an object tree of the XML document. This code locates the node in the object tree that corresponds to the article element of the XML document. The getNodeValue() method retrieves values of the attributes of the article node. The code compares the values of the attributes with those of the tag handler fields. The code removes the node whose attribute matches the tag handler field values by calling the removeChild() method. Finally, the code calls the transform() method of the Transformer object to transform the object tree back to the XML document.


Creating the Files to Rate Articles

An end user with user role can rate an article after viewing its contents. All end users can view article ratings. The files that allow end users to rate articles and view article ratings are:

  • DoRateArticle.jsp: Uses the <techdoc:doratearticle/> custom tag to rate articles.

  • DoRateArticleTag.java: Implements the <techdoc:doratearticle/> custom tag to record article ratings in the articlelist.xml file.

  • ArticleRatings.jsp: Uses the <techdoc:showarticleratings/> custom tag to display article ratings.

  • ShowArticleRatingsTag.java: Implements the <techdoc:showarticleratings/> custom tag to retrieve ratings from the articlelist.xml file.

Creating the DoRateArticle JSP Page

An end user with user role can rate articles in the View Articles page of the online article processing application. When an end user clicks the Rate button after specifying a rating for an article, the View Articles page submits the information to the DoRateArticle JSP page. The DoRateArticle JSP page uses the <techdoc:doratearticle/> custom tag to record the rating.

Listing 5-23 shows the code for the DoRateArticle.jsp file:

Listing 5-23: The DoRateArticle.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc" %>
<html>
<head>
<title>Article Rating Form</title>
</head>
<body>
<%
/*Retrieve end user role from session*/
String temprole=(String)session.getAttribute("role");
/*Check whether role is user*/
if("user".equals(temprole))
{
   %>
   <!--For user role, use header custom tag to display banner-->
   <techdoc:header subheading="Article Rating Result"/>
   <%
   /*Retrieve article category, article ID, and rating from request object*/
   String tempcategory =request.getParameter("category");
   String temparticleid=request.getParameter("articleid");
   String temprating=request.getParameter("rating");
   /*Check whether all required information are provided*/
   if(!(tempcategory==null || temparticleid ==null || temprating == null))
   {
      %>
      <Center>
      <!--Use doratearticle tag to rate article-->
      <techdoc:doratearticle category="<%=tempcategory%>"
      articleid="<%=temparticleid%>"
      userid="<%=(String)session.getAttribute("userid")%>"
      rating="<%=temprating%>"/></Cener>
      <%
     }
      %>
      <p align="center">&nbsp;</p>
      <p align="center"><a href="UserPage.jsp">Back to user page</a></p>
      <!--Use footer custom tag to display copyright information-->
      <techdoc:footer/>
      <%
   }
   %>
   </body>
   </html>
End example

Download this listing.

The above code uses the request object to retrieve the category, article ID, and rating parameters. The code uses the session object to retrieve the user ID of the end user. The <techdoc:doratearticle/> custom tag of the above code accepts the category, article ID, and rating parameters along with the user ID value as attributes.

Creating the DoRateArticleTag Tag Handler

The DoRateArticleTag tag handler implements the <techdoc:doratearticle/> custom tag. The tag handler retrieves the article ID, category, rating, and user ID values that are specified as custom tag attributes and adds the rating to the articlelist.xml file.

Listing 5-24 shows the content of the DoRateArticleTag.java file:

Listing 5-24: The DoRateArticleTag.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
import java.util.*;
import java.net.*;
public class DoRateArticleTag extends TagSupport
{
  /*Declare tag attributes*/
   private String category="";
   private String articleid="";
   private String rating="";
   private String userid="";
  /*Define setXXX() methods for tag attributes*/
   public void setCategory(String String_1)
   {
      category=String_1;
   }
   public void setArticleid(String String_1)
   {
      articleid=String_1;
   }
   public void setRating(String String_1)
   {
      rating=String_1;
   }
   public void setUserid(String String_1)
   {
      userid=String_1;
   }
        /*Define getXXX() methods for tag attributes*/
   public String getCategory()
   {
      return category;
   }
   public String getArticleid()
   {
      return articleid;
   }
   public String getRating()
   {
      return rating;
   }
   public String getUserid()
   {
      return userid;
   }
public int doStartTag()
   {
   try
     {
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/fifth/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the articlelistpath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      String articlepath = prop.getProperty("articlelistpath");
      /*Create object of DocumentBuildeFactory, using newInstance() method of DocumentBuilderFactory */
      DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
      /*Create object of DocumentBuilder using the newDocumentBuilder() method of DocumentBuilderFactory */
      DocumentBuilder docb = docbfact.newDocumentBuilder();
      /*Parse the articlelist.xml document and obtain a Document object*/
      Document doc = docb.parse(new FileInputStream(articlepath));
      /*Obtain a NodeList object that represents the elements of the XML file with name articlelist*/
      NodeList nluserlist = doc.getElementsByTagName("articlelist");
      Node doce = nluserlist.item(0);
      NodeList nl1 = doce.getChildNodes();
      /*Iterate through the NodeList object*/
      for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
      {
         /*Obtain the Node object by calling the item() method of NodeList*/
         Node n = nl1.item(int_1);
         if((n.getNodeName()).equals("article"))
         {
            /*Obtain the NamedNodeMap object that represents the attributes of the article element*/
            NamedNodeMap nnp= n.getAttributes();
            /*Get values for the category and article ID attributes*/
            String tempcategory=(nnp.getNamedItem("category")).getNodeValue();
            String temparticleid=(nnp.getNamedItem("articleid")).getNodeValue();
            /*Check retrieved values with end user specified values*/
            if((getCategory()).equals(tempcategory)&& (getArticleid()).equals(temparticleid))
            {
               /*Retrieve the child node*/
               NodeList nl2 = n.getChildNodes();
               Node articlenode = nl2.item(1);
               /*Create a rating element*/
               Element newElement = doc.createElement("rating");
               /*Set end user specified ratings as attribute*/
               newElement.setAttribute("userid", getUserid());
               newElement.setAttribute("rating", getRating());
               /*Append the child node to its parent article node*/
               articlenode.appendChild(newElement);
            }

         }
      }
      /*Create a TransformerFactory by calling the newInstance() method of TransformerFactory class*/
     TransformerFactory tFactory = TransformerFactory.newInstance();
     /*Obtain a Transformer object by calling the newTransformer() method of TransformerFactory class*/
     Transformer transformer = tFactory.newTransformer();
     /*Set output property of Transformer object*/
     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     /*Specify the source of the transformation*/
     DOMSource source = new DOMSource(doc);
     /*Create the StreamResult holder for  transformation to the articlelist.xml file*/
     StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(articlepath)));
     /*Perform the transformation*/
     transformer.transform(source, result);
     /*Print out success message*/
     JspWriter out = pageContext.getOut();
     out.print("Your rating has been successfully recorded.");
   }
   catch(IOException ioe)
   {
   System.out.println("Error in HeaderTag: " + ioe);
   }
   catch(Exception oe)
   >{
      System.out.println("Error in HeaderTag: " + oe);
    }
     return(SKIP_BODY);
   }
}
End example

Download this listing.

The above code creates the DoRateArticleTag tag handler. The category, articleid, rating, and userid fields represent the attributes of the <techdoc:doratearticle/> custom tag. The accessor and mutator methods retrieve and set the attributes of the <techdoc:doratearticle/> custom tag. The code parses the articlelist.xml file and creates an object tree of the XML document. The code locates the article node of the object tree whose attribute corresponds to the category and article ID attributes of the custom tag. The createElement() method of the Document object adds a node with the name, rating, within the article node. The setAttribute() method of the Element object sets the userid and rating values as attributes of the rating node. Finally, the code calls the transform() method of the Transformer object to transform the object tree back to the articlelist XML document.

Creating the ArticleRatings JSP Page

The ArticleRatings JSP creates the Article Ratings page. To display the article ratings, the ArticleRatings JSP uses the <techdoc:showarticleratings/> custom tag.

Listing 5-25 shows the content of the ArticleRatings.jsp file:

Listing 5-25: The ArticleRatings.jsp File
Start example
<!--Use taglib directive to include technicaldocs-taglib.tld TLD-->
<%@page import="javax.xml.parsers.*,java.net.*,java.io.*,org.w3c.dom.*"%>
<%@ taglib uri="WEB-INF/tlds/technicaldocs-taglib.tld" prefix="techdoc" %>
<html>
<head>
<title>Article Search Result Page</title>
</head>
<body>
<%
/*Retrieve end user role from session*/
String temprole=(String)session.getAttribute("role");
 /*Check for roles*/
if("administrator".equals(temprole) || "user".equals(temprole))
{
   %>
   <!--Use header custom tag to display banner-->
   <%String tempsubheading="Article Ratings";%>
   <techdoc:header subheading="<%=tempsubheading%>"/>
   <!--Page design to display article ratings-->
   <div align="justify">
   <table border="1" cellpadding="0" cellspacing="0" width="100%" >
   <tr>
   <td colspan="2" bgcolor="#008080">
   <p align="center"><i><font
 color="#FFFFFF"><b>Articles</b></font>
 </i></p>
   </td>
   <td colspan="2" bgcolor="#008080">
   <p align="center"><i><font
 color="#FFFFFF"><b>Ratings</b></font></i></p>
   </td>
   </tr>
   <!--Use showarticleratings tag to rate article-->
   <techdoc:showarticleratings/>
   </table>
   </div>
   <p align="center">&nbsp;</p>
   <%
   /*For administrator role, display hyperlink to AdminPage.jsp*/
   if(temprole.equals("administrator"))
   {
      %>
      <p align="center"><a href="AdminPage.jsp">Back to administration
      page</a></p>
      <%
   }
   %>
   <%
   /*For a user role, display hyperlink to UserPage.jsp*/
   if(temprole.equals("user"))
   {
      %>
      <p align="center"><a href="UserPage.jsp">Back to user page</a></p>
      <%
   }
}
%>
<!--Use footer custom tag to display copyright information-->
<techdoc:footer/>
</body>
</html>
End example

Download this listing.

The above code uses the <techdoc:showarticleratings/> custom tag to display article ratings in tabular format.

Figure 5-7 shows the Article Ratings page of the online article processing application:

Click To expand: This figure shows the Article Ratings page that displays ratings of articles in tabular format.
Figure 5-7: The Article Ratings Page

Creating the ShowArticleRatingsTag Tag Handler

The ShowArticleRating tag handler implements the <techdoc:showarticleratings/> custom tag. The tag handler parses the articlelist.xml file to retrieve information about the category, article ID, article rating, and user ID of the end user who rated the article.

Listing 2-26 shows the ShowArticleRating.java file:

Listing 5-26: The ShowArticleRating.java File
Start example
package technicaldocs;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.net.*;
import java.util.*;
public class ShowArticleRatingsTag extends TagSupport {
public int doStartTag()
  {
   try
   {
      /*Create a URL object to load the properties file*/
      URL url=new URL("http://127.0.0.1:8080/fifth/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the articlelistpath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      String articlepath = prop.getProperty("articlelistpath");
      /*Obtain JSPWriter object to print out response*/
      JspWriter out = pageContext.getOut();
      /*Obtain session object*/
      HttpSession session = pageContext.getSession();
      /*Retrieve role from session object*/
      String temprole = (String)session.getAttribute("role");
      /*Use the newInstance() method of DocumentBuilderFactory object to obtain a
      DocumentBuilderFactory object*/
      DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
     /*Obtain a DocumentBuilder object by calling the newDocumentBuilder() method of
     DocumentBuilderFactory*/
     DocumentBuilder docb = docbfact.newDocumentBuilder();
     /*Parse the articlelist XML document*/
     Document doc = docb.parse(new FileInputStream(articlepath));
     /*Obtain a NodeList object that represents the elements of the XML file with name
     articlelist*/
     NodeList nluserlist = doc.getElementsByTagName("articlelist");
     /*Call the item() method to obtain a Node object*/
      Node doce = nluserlist.item(0);
      /*Retrieve the child node*/
      NodeList nl1 = doce.getChildNodes();
      /*Iterate through the NodeList object*/
      for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
      {
         Node n = nl1.item(int_1);
         /*Check for the article node*/
         if((n.getNodeName()).equals("article")
      )
      {
         /*Retrieve attributes for the node*/
         NamedNodeMap nnp= n.getAttributes();
         /*Retrieve category and article ID attributes for the node*/
         String tempcategory=(nnp.getNamedItem("category")).getNodeValue();
         String temparticleid=(nnp.getNamedItem("articleid")).getNodeValue();
         /*Display category and article ID attributes*/
         out.println("<tr>");
         out.println("<td><B>Category:</B>
         "+tempcategory+"</td><td><B>Article ID:</B>
         "+temparticleid+"</td>");
         out.println("<td>");
         out.println("<table border=\"0\"><tr>");
         /*Retrieve child nodes*/
         NodeList nl2 = n.getChildNodes();
         /*Obtain Node object of child node*/
         Node articlenode = nl2.item(1);
         NodeList nl3 = articlenode.getChildNodes();
         /*Iterate through the NodeList object*/
         for(int int_2 = 0; int_2 < nl3.getLength(); int_2 ++)
         {
            /*Check for rating node*/
            Node articleratingnode = nl3.item(int_2);
            if((articleratingnode.getNodeName()).equals("rating"))
            {
               /*Retrieve userid and rating attributes*/
               NamedNodeMap nnp1 = articleratingnode.getAttributes();
               /*Display userid and ratings*/
               out.println("<td><B>User ID:</B>
               "+(nnp1.getNamedItem("userid")).getNodeValue()+"</td>");
               out.println("<td><B>Rating:</B>
               "+(nnp1.getNamedItem("rating")).getNodeValue()+"</td>");}
             } out.println("</table></tr>");
             out.println("</td>");out.println("</tr>");
          }
        }
      }
      catch(IOException ioe)
      {
         System.out.println("Error in HeaderTag: " + ioe);
      }
      catch(Exception oe)
      {
        System.out.println("Error in HeaderTag: " + oe);
      }
      return(SKIP_BODY);
   }
}
End example

Download this listing.

The above code creates the ShowArticleRating tag handler. This code uses a DocumentBuilder object to parse the articlelist.xml file. The code uses the getNodeValue() method to retrieve the category and article ID of all the articles. For articles with ratings, the code retrieves the rating and userid attributes. Finally, the code displays the retrieved information in tabular format.


Creating the Property File

The online article processing application uses a property file that stores the path to the XML files of the application. The following code shows the path.properties property file of the application:

userlistpath=c:/Chp5/code/xml/userlist.xml
articlelistpath=c:/Chp5/code/xml/articlelist.xml

The above code contains the following properties:

  • userlistpath: Specifies the path to the userlist.xml file.

  • articlelistpath: Specifies the path to the articlelist.xml file.

Note

Change the values of the userlistpath and articlelistpath properties of the path.properties file to the path of the XML documents as stored in your computer.


Unit Testing

You need to deploy and test the online article processing application on the Sun Java System Application Server Platform Edition 8. You can download this application server from:

http://java.sun.com/j2ee/1.4/download.html

Note

To install the Sun Java System Application Server Platform Edition 8, you need to install Java 2 Standard Edition (J2SE) 1.4.2 on the computer.

To deploy the online article processing application:

  1. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Start Default Server from the Start menu to start the application server.

  2. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Deploytool from the Start menu to open the Deployment Tool window.

  3. Select New->Application from the File menu of the Deployment Tool window. The New Application dialog box appears.

  4. Click Browse in the New Application dialog box to display another New Application dialog box.

  5. Select the directory where you want to save the .ear file in the Look In combo box.

  6. Enter the name of the .ear file as OnlineArticleProcessingAppl in the File Name text box, as shown in Figure 5-8:

    Click To expand: This figure shows the New Application dialog box in which you can specify the name of the application file and the location to store it.
    Figure 5-8: The New Application Dialog Box

  7. Click the New Application button to return to the previous New Application dialog box.

  8. Click OK to create the new application.

  9. Select New->Web Component from the File menu of the Deployment Tool window. The New Web Application Wizard-Introduction dialog box appears.

  10. Click Next. The New Web Application Wizard-Web Archive (WAR) File dialog box appears.

  11. Click Edit Contents in the New Web Application Wizard-WAR File dialog box. The Edit Contents of WebApp dialog box appears.

  12. Select all the JSP files and the path.properties file of the application in the Available Files pane and click Add. Select the class files of the tag handlers stored in the technicaldocs directory and click Add. You also need to select the tlds directory and click Add. The Contents of WebApp pane displays the files you added, as shown in Figure 5-9:

    Click To expand: This figure shows the Edit Contents of WebApp dialog box that displays the files of the online article processing application.
    Figure 5-9: The Edit Contents of WebApp Dialog Box

  13. Click OK to add the files to the Web applicationWAR file.

  14. Click Next in the New Web Application Wizard-WAR File dialog box. The New Web Application Wizard-Choose Component Type dialog box appears.

  15. Select the JSP Page radio button and click Next. The New Web Application Wizard-Component General Properties dialog box appears.

  16. Select LoginPage.jsp from the JSP Filename drop-down list. The remaining fields get automatically populated with values. Figure 5-10 shows the New Web Application Wizard- Component General Properties dialog box:

    Click To expand: This figure shows the New Web Application Wizard-Component General Properties dialog box in which you specify the main page of the application.
    Figure 5-10: The New Web Application Wizard-Component General Properties Dialog Box

  17. Click Finish.

  18. In the Deployment Tool window, specify /fifth as the context root of the application in the Context Root text field, as shown in Figure 5-11:

    Click To expand: This figure shows the Context Root text field of the Deployment Tool window in which you can specify the context root of the application.
    Figure 5-11: The Deployment Tool Window

  19. Select Save from the File menu of the Deployment Tool window to save the application.

  20. Select Deploy from the Tools menu. The Deploy Module OnlineArticleProcessingAppl dialog box appears.

  21. Specify the application server user name and password in the User Name and Password fields and click OK.

  22. The Distribute Module dialog box appears and indicates the successful deployment of the application.

To test the deployed application:

  1. Type the following URL in the address bar of the browser:

    http://localhost:8080/fifth/LoginPage.jsp

  2. The Logon page of the application appears. Specify user1 in the User ID text field and puser1 in the Password field, as shown in Figure 5-12:

    Click To expand: This figure shows the Logon Page of the application in which you can specify your user ID and password to log on.
    Figure 5-12: Specifying Logon Information

  3. Click Logon to log on as an administrator. The user interface of the DoLogin JSP page displays a hyperlink to the Administer Article page, as shown in Figure 5-13:

    Click To expand: This figure shows the user interface of the DoLogin JSP page that displays the Administrator main page hyperlink.
    Figure 5-13: The User Interface of the DoLogin JSP Page for Administrator Role

  4. Select the Administrator main page hyperlink. The Administer Article page appears.

  5. In the Add Article table of the Administer Article page, specify information about an article you want to add, as shown in Figure 5-14:

    Click To expand: This figure shows the Add Article table of the Administer Article page in which you can specify information to add a new article.
    Figure 5-14: The Add Article Table of the Administer Article Page

  6. Click Submit to add the article. The DoAddArticle JSP page displays a user interface with a message indicating that the article has been successfully added. Figure 5-15 shows the user interface provided by the DoAddArticle JSP page:

    Click To expand: This figure shows the DoAddArticle JSP page that displays a message to indicate that the article has been successfully added.
    Figure 5-15: User Interface of the DoAddArticle JSP Page

  7. Check the articlelist.xml file to ensure that the article information has been added.

  8. Click the Back to administration page hyperlink to return to the Administer Article page.

  9. In the Administer Article page, select a category to search for articles and click Submit. The View Article page displays the articles that match the search criterion. Figure 5-16 shows the View Article page:

    Click To expand: This figure shows the View Article page that displays the articles that match your search criterion.
    Figure 5-16: The View Article Page

  10. Modify the content of the article in the Article text area and click Update. To delete the article, click the Delete button in the View Article page.

  11. Select the Logout hyperlink in the Administer Article page to logout from the application.

  12. Specify user2 and puser2 in the Logon ID and Password fields of the Logon Page to log on as an end user with user role.

  13. The user interface of the DoLogin JSP page displays the hyperlink to the User Page, as shown in Figure 5-17:

    Click To expand: This figure shows the user interface of the DoLogin JSP page that displays the User main page hyperlink.
    Figure 5-17: The User Interface of the DoLogin JSP Page for User Role

  14. Select the User main page hyperlink. The User Page appears, as shown in Figure 5-18:

    Click To expand: This figure shows the User Page of the online article processing application in which you can search an article to view its contents.
    Figure 5-18: Searching an Article

  15. Select an article category and click Submit. The View Articles page displays the articles of the specified category.

  16. Rate an article in the Rating text field, as shown in Figure 5-19:

    Click To expand: This figure shows the View Articles page in which you can view and rate articles.
    Figure 5-19: Rating an Article

  17. Click the Rate button to submit the rating. The DoRateArticle JSP page displays a user interface to indicate that the rating has been successfully recorded. Figure 5-20 shows the user interface of the DoRateArticle JSP page:

    Click To expand: This figure shows the user interface of the DoRateArticle JSP page that displays the message, Your rating has been successfully recorded.
    Figure 5-20: User Interface of the DoRateArticle JSP Page

  18. Select the Back to user page hyperlink in the user interface of the DoRateArticle JSP page.

  19. In the User Page, select the View Article Ratings hyperlink. The Article Ratings page displays the ratings of articles, as shown in Figure 5-21:

    Click To expand: This figure shows the Article Ratings page that displays ratings of articles.
    Figure 5-21: Displaying Article Ratings

  20. Select the Back to user page hyperlink to return to the User Page of the online article processing application.

  21. In the User Page, select the Logout hyperlink to log out of the application.


Point 6: Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications

JavaServer Pages Standard Tag Library (JSTL) is a collection of standard tags that implement functions common to JSP applications. For example, instead of coding JSP pages to parse and access XML documents, you can use the XML tags of JSTL to parse and access XML documents. JSP pages can use XML tags along with the core tags of JSTL to access contents of XML documents. JSTL provides multiple Tag Library Descriptors (TLDs) that define groups of tags based on the functioning of tags. For example, the XML tags of JSTL are defined in the jstl-x TLD. The XML tags are grouped as core, flow control, and transformation tags, based on their functioning.

This chapter discusses an online news application that uses the core and XML tags of JSTL to display news.

Requirements of the Online News Application

The online news application allows end users to view news. The home page of the application displays news headlines. An end user needs to log on to view the complete news. The application allows end users to search news by category, date, and keywords. XML files of the news application store information about end users and news. The XML files of the application are:

  • userlist.xml: Stores end user logon ID and password values.

  • newslist.xml: Stores news information, such as headline, date, category, and content.

The JSP pages of the online news application render the user interface of the application. The JSP pages use the tags of JSTL to parse the userlist and newslist XML documents to authenticate user information and display news. The JSP pages of the news application are:

  • MainPage.jsp: Renders the main page of the application that displays news headlines and the fields to accept user ID and password values from an end user.

  • DoLogon.jsp: Parses the userlist.xml file to authenticate user ID and password values of an end user.

  • DoLogout.jsp: Invalidates the current session and forwards log on request to MainPage.jsp.

  • MainNewsPage.jsp: Displays news headlines as hyperlinks.

  • NewsDetailPage.jsp: Displays the complete content of the news.

  • SearchNewsPage.jsp: Allows an end user to search news by category, date, or keyword.

  • DoSearchNews.jsp: Displays the headlines of news that matches the search criteria specified by an end user.

Figure 6-1 shows the architecture of the online news application:

Click To expand: This figure shows the various JSP files used in the online news application and the sequence in which they are used.
Figure 6-1: Architecture of the Online News Application


Creating the XML Files

The online news application stores information about end users and news in XML files. The userlist.xml file stores user ID and password values of end users. Listing 6-1 shows the content of the userlist.xml file:

Listing 6-1: The userlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<userlist>
<user name="Peter" password="peter">
</user>
<user name="Sara" password="sara">
</user>
</userlist>
End example

Download this listing.

The above code contains the userlist root element that includes user elements. Each user element contains a name and password attribute. The name and password attributes contain values of the user ID and password of an end-user.

The newslist.xml file of the online news application stores news information. The XML file contains news elements that contain the news data.

Listing 6-2 shows the content of the newslist.xml file:

Listing 6-2: The newslist.xml File
Start example
<newslist>
<news id="1">
<date>3-7-2004</date>
<category>Sports</category>
<heading>Rain delays wimbeldon quarter final match.</heading>
<main>
Rain delayed start of the Wimbeldon quarter final match by two hours. When the play finally started,
both the players, James Smith and Andrew Hudson, were locked at two sets each before they broke for lunch.
</main>
</news>
<news id="2">
<date>3-7-2004</date>
<category>Politics</category>
<heading>US state of Georgia to host G8 summit</heading>
<main>
The resort town of Sea Island in the US state of Georgia will host the G8 summit scheduled from
June 8 to June 10. The state and government heads of Britain, Canada, France, Germany, Italy,
Japan, Russia, and the United States will discuss issues on international reforms in this summit.
</main>
</news>
<news id="3">
<date>26-6-2004</date>
<category>Entertainment</category>
<heading>British band rocks New York.</heading>
<main>The British band, Sunshine in Midnight, performed in front of packed audience in
Rock block of Hess Express in NY. Around 20,000 fans swayed to the live performance that
included the legendry number, Check me out of the band.</main>
</news>
</newslist>
End example

Download this listing.

The above code contains the newslist root element that includes news elements. Each news element contains an id attribute that uniquely identifies the news. The news element contains the date, category, heading, and main subelements. The date element contains the date of publication of the news. The category element contains the news category, such as Sports, Entertainment, and Politics. The heading and main elements contain the heading and content of the news.


Creating the MainPage JSP Page

The MainPage JSP page renders the home page of the online news application. The MainPage JSP page displays the news headlines and the fields to accept the user ID and password of an end-user.

Listing 6-3 shows the content of the MainPage.jsp file:

Listing 6-3: The MainPage.jsp File
Start example
<html>
<head>
<title>Online News</title>
</head>
<body>
<div align="center">
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em>Online News
</em></strong></font></h2></td>
</tr>
</table>
<p>&nbsp;</p>
<p><em></em></p>
</div>
<p align="center">&nbsp;</p>
<!--Display form to post logon information to DoLogon.jsp-->
<form action="DoLogon.jsp">
<center>
<table border="1" width="300" cellspacing="0" cellpadding="0" height="81">
<!--Display user ID text field-->
<tr>
<td width="50%" bgcolor="#FFFFFF"><div align="center"><font
color="#000080"><b>User ID</b></font></div></td>
<td width="50%"><input name="txtusername"></td>
</tr>
<!--Display password field-->
<tr>
<td width="50%" bgcolor="#FFFFFF"><div align="center"><font
color="#000080"><b>Password</b></font></div></td>
<td width="50%"><input type="password" name="txtpassword" size="20"></td>
</tr>
<tr>
<td width="50%"><div align="center">
<input type="submit" value="Logon" name="B1">
</div></td>
<td width="50%"><input type="reset" value="Reset" name="B2"></td>
</tr>
</table>
</center>
</form>
<p>&nbsp;</p>
<center>
<table width="48%" border="1" cellpadding="0" cellspacing="0" bordercolor="#0000FF">
<tr>
<td width="100%" bgcolor="#FFFFFF"><div align="center"><font
color="#FF0000"><b>Todays headlines</b></font></div></td>
</tr>
<!--Use taglib directive to include JSTL core and XML tags-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml"
prefix="x"%>
<!--Parse newslist.xml file and store result in newslist variable in application scope-->
<c:if test="${empty applicationScope.newslist}" >
<c:import url="http://localhost:8080/news/xml/newslist.xml" var="xml"/>
<x:parse doc="${xml}" var="newslist" scope="application"/>
</c:if>
<!--Retrieve date element value for each news element and store in tempdate variable in request scope-->
<x:forEach var="heading" select="$newslist/newslist/*">
<c:set var="tempdate" scope="request">
<x:out select="$heading/date"/>
</c:set>
<%
/*Retrieve current date in string*/
java.util.Date currdate = new java.util.Date();
String tempdate=""+currdate.getDate()+"-"+(currdate.getMonth()+1)+"-"+(1900+currdate.getYear());
/*Retrieve date stored in request*/
String tempnewsdate=(String)request.getAttribute("tempdate");
if(tempdate.equals(tempnewsdate))
{
   /*Compare current date with date retrieved from object. Display  headings for matching dates*/
   %>
   <tr>
   <td width="100%"><div align="center"><font color="#000080"><b>
   <x:out select="$heading/heading"/></b></font></div></td>
   </tr>
   <%
}
%>
</x:forEach>
</table>
</center>
</body>
</html>
End example

Download this listing.

The above code creates the MainPage JSP page. The code displays the User ID and Password fields to accept user information. The taglib directives include the JSTL core and XML tag libraries in the JSP page. The <c:import> tag stores the newslist XML document in an xml variable. The <x:parse> tag parses the XML document and stores the result in a newslist variable. The <x:forEach> tag retrieves the date of publication of news and stores the date value in the tempdate variable. The code uses the Date class to retrieve the current date and stores the date value in the tempnewsdate variable. The code compares the date value stored in the tempdate variable with the value stored in the tempnewsdate variable. For matching values, the code uses the <x:out > tag to display the news headlines.

Figure 6-2 shows the user interface of the MainPage JSP page:

Click To expand: This figure shows the user interface of the MainPage JSP page that displays the fields to obtain user information and the news headlines for the current date.
Figure 6-2: The MainPage JSP Page


Creating the DoLogon and DoLogout JSP Pages

The DoLogon JSP page authenticates the user ID and password of end users with the values stored in the userlist XML document. The DoLogon JSP page uses the core and XML tags of JSTL to access the userlist XML document.

Listing 6-4 shows the content of the DoLogon.jsp file:

Listing 6-4: The DoLogon.jsp File
Start example
<html>
<head>
<title>Do Logon</title>
</head>
<body>
</body>
</html>
<%
/*Use request object to retrieve user ID and password*/
 String tempusername = request.getParameter("txtusername");
 String temppassword = request.getParameter("txtpassword");
/*Flag boolean variable, success to false*/
 boolean success=false;
%>
<!--Use taglib directive to include JSTL core and XML tags-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml"
prefix="x" %>
<!--If userlist variable is empty, parse userlist.xml file and store result in userlist
variable in application scope-->
<c:if test="${empty applicationScope.userlist}" >
<c:import url="http://localhost:8080/news/xml/userlist.xml" var="xml" />
<x:parse doc="${xml}" var="userlist" scope="application" />
</c:if>
<x:forEach var="user" select="$userlist/userlist/*">
<!--For all user element of XML document, set value of name attribute in tempuser variable in request scope-->
<c:set var="tempuser" scope="request">
<x:out select="$user/@name"/>
</c:set>
<!--For all user element of XML document, set value of password attribute in temppass variable in request scope-->
<c:set var="temppass" scope="request">
<x:out select="$user/@password"/>
</c:set>
<%
/*Check user ID and password variable stored in tempuser and temppass variables with end user specified values*/
if(tempusername.equals((String)request.getAttribute("tempuser"))&&
temppassword.equals((String)request.getAttribute("temppass")))
{
   /*If user ID and password matches, flag success to true*/
   success=true;
}
%>
</x:forEach>
<%
if(success)
{
   /*For success value true, store user ID in session*/
   %>
   <c:set var="username" value="<%=tempusername%>" scope="session"/>
   <!--Forward request to MainNewsPage.jsp-->
   <jsp:forward page="MainNewsPage.jsp"/>
   <%
}
else
{
   /*For success value false, forward request to MainPage.jsp*/
   %>
   <jsp:forward page="MainPage.jsp"/>
   <%
}
%>
End example

Download this listing.

The above code creates the DoLogon JSP page. The taglib directives import the core and XML tag libraries in the JSP page. The <x:parse> tag parses the userlist XML document and stores the result in a userlist variable. The <c:set> tag stores values of the name and password attributes in the tempuser and temppass variables. The code compares the values of the tempuser and temppass variables with the values specified by the end user. If the user ID and password values match, the code forwards the request to the MainNewsPage.jsp file. If the user ID and password values do not match, the code forwards the request to the MainPage.jsp file.

The DoLogout JSP page of the online news application is called when an end user clicks the Logout hyperlink in the application. The DoLogout JSP page invalidates the current session and forwards the request to the MainPage.jsp file. Listing 6-5 shows the content of the DoLogout.jsp file:

Listing 6-5: The DoLogout.jsp File
Start example
<%
/*Invalidate current session*/
session.setAttribute("username","");
session.invalidate();
%>
<!--Forward request to MainPage.jsp page-->
<jsp:forward page="MainPage.jsp"/>
End example

Download this listing.


Creating the MainNewsPage JSP Page

The MainNewsPage JSP page displays the news headlines as hyperlinks. End users can select the hyperlinks to view the content of the news.

Listing 6-6 shows the content of the MainNewsPage.jsp file:

Listing 6-6: The MainNewsPage.jsp File
Start example
<html>
<head>
<title>Online News</title>
</head>
<body>
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em><font
color="#FFFFFF">Online</font>Online News
</em></strong></font></h2></td>
</tr>
</table>
<p align="center"><b></b></p>
<center>
<!--Display user ID from session object-->
<table border="1" width="300" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="50%" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#000080"><b>User ID </b></font></div></td>
<td width="50%" height="1"><div
align="center"><%=(String)session.getAttribute("username")%></div></td>
</tr>
</table>
</center>
<!--Display hyperlinks to DoLogout.jsp and SearchNewsPage.jsp files-->
<p align="center"><a href="DoLogout.jsp">Logout</a></p>
<p align="center"><a href="SearchNewsPage.jsp">Search news </a></p>
<Center>
<!--Page design to display hyperlinks of headlines-->
<table border="1" width="48%" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" bgcolor="#FFFFFF"><div align="center"><font
color="#000080"><b>Headlines</b></font></div></td>
</tr>
<!--Use taglib directive to include JSTL core and XML tags-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml"
prefix="x" %>
<!--If newslist variable is empty, parse newslist.xml file and store result in newslist
variable in application scope-->
<c:if test="${empty applicationScope.newslist}" >
<c:import url="http://localhost:8080/news/xml/newslist.xml" var="xml"/>
<x:parse doc="${xml}" var="newslist" scope="application"/>
</c:if>
<!--Store news date in tempdate variable within request scope-->
<x:forEach var="heading" select="$newslist/newslist/*">
<c:set var="tempdate" scope="request">
<x:out select="$heading/date"/>
</c:set>
<%
/*Retrieve current date in String*/
java.util.Date currdate = new java.util.Date();
String tempdate=""+currdate.getDate()+"-"+(currdate.getMonth()+1)+"-"+(1900+currdate.getYear());
/*Retrieve date stored in request*/
String tempnewsdate=(String)request.getAttribute("tempdate");
if(tempdate.equals(tempnewsdate))
{
   /*Compare current date with date retrieved from object. Display headings for matching dates.*/
   %>
   <tr>
   <!--Display headline hyperlinks to NewsDetailPage.jsp. Append an id query parameter to URL-->
   <td width="100%"><center><a href="NewsDetailPage.jsp?id=<x:out
   select="$heading/@id"/>"><x:out
   select="$heading/heading"/></a></center></td>
   </tr>
   <%
}
%>
</x:forEach>
</table>
</center>
</body>
</html>
End example

Download this listing.

The above code creates the MainNewsPage JSP page. The taglib directives of the above code import the core and XML tag libraries of JSTL in the JSP page. The <x:parse> tag parses the newslist XML document and stores the result in a newslist variable. For each news element of the newslist XML document, the code uses the <c:set> tag to store the date of publication of the news in the tempdate variable. The code uses the Date object to obtain the current date and compares the date value stored in the tempdate variable. For matching date, the code displays a hyperlink to the NewsDetailPage.jsp file. The <x:out select="$heading/@id"/> tag sets the news ID as a query string parameter of the hyperlink. The <x:out select="$heading/heading"/> tag displays the news headline as the text of the hyperlink.

Figure 6-3 shows the user interface rendered by the MainNewsPage JSP page:

Click To expand: This figure shows the user interface of the MainNewsPage JSP page that displays the news headlines as hyperlinks.
Figure 6-3: The MainNewsPage JSP Page


Creating the NewsDetailsPage JSP Page

The NewsDetailsPage JSP page displays the complete news for the headline that an end user selects. The NewsDetailsPage JSP page displays the headline, date, category, and content of the news.

Listing 6-7 shows the content of the NewsDetailsPage.jsp file:

Listing 6-7: The NewsDetailsPage.jsp File
Start example
<html>
<head>
<title>Online News</title>
</head>
<body>
<!--Page design to display news-->
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em><font
color="#FFFFFF">Online</font>Online News
</em></strong></font></h2></td>
</tr>
</table>
<center>
<table border="1" width="300" cellspacing="0" cellpadding="0" height="1">
<!--Retrieve user ID value from session and display value-->
<tr>
<td width="50%" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#000080"><b>User ID</b></font></div></td>
<td width="50%" height="1"><div align="center"><font
color="#000080"><b><%=(String)session.getAttribute("username")%></b></
font></div></td>
</tr>
</table>
</center>
<!--Display hyperlinks to DoLogout.jsp,MainNewsPage.jsp, and SearchNewsPage.jsp files-->
<p align="center"><a href="DoLogout.jsp">Logout</a></p>
<p align="center"><a href="MainNewsPage.jsp">View headlines </a></p>
<p align="center"><a href="SearchNewsPage.jsp">Search news </a></p>
<!--Use taglib directive to include JSTL core and XML tags-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml"
prefix="x"%>
<!--If newslist variable is empty, parse newslist.xml file and store result in newslist
variable in application scope-->
<c:if test="${empty applicationScope.newslist}">
<c:import url="http://localhost:8080/news/xml/newslist.xml" var="xml"/>
<x:parse doc="${xml}" var="newslist" scope="application" />
</c:if>
<!--Page design to display news in tabular format-->
<table border="1" width="96%" cellspacing="0" cellpadding="0" height="159">
<tr bgcolor="#FFFFFF">
<td width="100%" height="19" colspan="2"><div align="center"><font
color="#FF0000"><b>News Date :<x:out
select="$newslist/newslist/news[@id=$param:id]/date"/></b></font></div></td>
</tr>
<!--Retrieve news ID from request object, to display headline of the news-->
<tr>
<td width="23%" height="19" bgcolor="#FFFFFF"><div align="center"><font
color="#000080"><b>Headline</b></font></div></td>
<td width="77%" height="19"><div align="center"><font
color="#000080"><b>
<x:out select="$newslist/newslist/news[@id=$param:id]/heading"/></b></font>
</div></td>
</tr>
<!--Retrieve news ID from request object, to dsplay category of the news-->
<tr>
<td width="23%" height="21" bgcolor="#FFFFFF"><div align="center"><font
color="#000080"><b>Category</b></font></div></td>
<td width="77%" height="21"><div align="center"><font
color="#000080"><b>
<x:out select="$newslist/newslist/news[@id=$param:id]/category"/>
</b></font></div></td>
</tr>
<!--Retrieve news ID from request object, to dsplay details of the news-->
<tr>
<td width="23%" height="94" bgcolor="#FFFFFF"><div align="center"><font
color="#000080"><b>News</b></font></div></td>
<td width="77%" height="94"><div align="center"><font
color="#000080"><b>
<x:out select="$newslist/newslist/news[@id=$param:id]/main"/></b></font>
</div></td>
</tr>
</table>
</body>
</html>
End example

Download this listing.

The above code renders the NewsDetailPage JSP page. The <x:parse > tag parses the newslist.xml file and stores the result in the newslist variable. The <x:out> tag of the code uses the headline ID passed as a query string to display news headline, category, and content.

Figure 6-4 shows the user interface rendered by the NewsDetailPage JSP page:

Click To expand: This figure shows the user interface of the NewsDetailPage JSP page that displays the news headline, category, and content of news selected by an end user.
Figure 6-4: The NewsDetailPage JSP Page


Creating the SearchNewsPage JSP Page

The SearchNewsPage JSP page allows end users to search for news by category, date, or keyword.

Listing 6-8 shows the content of the SearchNewsPage.jsp file:

Listing 6-8: The SearchNewsPage.jsp File
Start example
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Online News</title>
</head>
<body>
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em><font
color="#FFFFFF">Online</font>Online News
</em></strong></font></h2></td>
</tr>
</table>
<p align="center"><b></b></p>
<center>
<table border="1" width="300" cellspacing="0" cellpadding="0" height="1">
<!--Retrieve user ID value from session and display value-->
<tr>
<td width="50%" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#000080"><b>User Name</b></font></div></td>
<td width="50%" height="1"><div align="center"><font
color="#000080"><b><%=(String)session.getAttribute("username")%></b></
font></div></td>
</tr>
</table>
</center>
<!--Display hyperlink to DoLogout.jsp file-->
<p align="center"><a href="DoLogout.jsp">Logout</a></p>
<!--Use taglib directive to include JSTL core and XML tags-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml"
prefix="x" %>
<!--If newslist variable is empty, parse newslist.xml file and store result in newslist
variable in application scope-->
<c:if test="${empty applicationScope.newslist}">
<c:import url="http://localhost:8080/news/xml/newslist.xml" var="xml"/>
<x:parse doc="${xml}" var="newslist" scope="application"/>
</c:if>
<center>
<table border="1" width="47%" height="86">
<!--Display form to search by category and post search values to DoSearchNews.jsp-->
<tr>
<td width="100%" height="30" align="left">
<form method="POST" action="DoSearchNews.jsp">
<!--Display Category drop-down list-->
<p align="center"><b>Category: </b>
<select size="1" name="txtcategory">
<!--Populate drop-down list with news category values-->
<x:forEach var="heading" select="$newslist/newslist/*">
<option value="<x:out select="$heading/category"/>"><x:out
select="$heading/category"/></option>
</x:forEach>
</select><input type="submit" value="Search" name="B1"><input type="reset"
value="Reset" name="B2"></p>
<!--Use hidden field to track query-->
<input type="hidden" name="txtaction" value="bycategory">
</form>
</td>
</tr>
<tr>
<td width="100%" height="19" align="left">
<!--Display form to search by keyword and post search values to DoSearchNews.jsp-->
<form method="POST" action="DoSearchNews.jsp">
<!--Display Keyword field-->
<p align="center"><b>Keyword:</b>
<input type="text" name="txtkeyword" size="22"><input type="submit" value="Search"
name="B1"><input type="reset" value="Reset" name="B2"></p>
<!--Use hidden field to track query-->
<input type="hidden" name="txtaction" value="bykeyword">
</form>
</td>
</tr>
<tr>
<td width="100%" height="19" align="left">
<!--Display form to search by date and post search values to DoSearchNews.jsp-->
<form method="POST" action="DoSearchNews.jsp">
<!--Display Date field-->
<p align="center"><b>Date:</b>
<input type="text" name="txtdate" size="20"><input type="submit" value="Search"
name="B1"><input type="reset" value="Reset" name="B2"></p>
<!--Use hidden field to track query-->
<input type="hidden" name="txtaction" value="bydate">
</form>
</td>
</tr>
</table>
</center>
</body>
</html>
End example

Download this listing.

The above code creates the SearchNewsPage JSP page. The taglib directive includes the JSTL core and XML tag libraries in the JSP page. The <c:import> tag stores the newslist XML document in an xml variable. The <x:parse> tag parses the XML document and stores the result in a newslist variable. The code displays the Category drop-down list, Keyword text field, and Date text field to allow end users to search for news. The Submit button of the search field submits search information to the DoSearchNews JSP page. The <x:out select="$heading/category"/> tag populates the category drop-down list with a news category retrieved from the newslist XML document.

Figure 6-5 shows the user interface of the SearchNewsPage JSP page:

Click To expand: This figure shows the user interface of the SearchNewsPage JSP page that displays the Category drop-down list, Keyword text field, and Date text field.
Figure 6-5: The SearchNewsPage JSP Page


Creating the DoSearchNews JSP Page

The DoSearchNews JSP page displays news headlines that match end user search in the form of hyperlinks. The DoSearchNews JSP page uses the core and XML tag libraries of JSTL to access and display contents of the newslist XML document.

Listing 6-9 shows the content of the DoSearchNews.jsp file:

Listing 6-9: The DoSearchNews.jsp File
Start example
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Online News</title>
</head>
<body>
<table width="830" height="71" border="0">
<tr>
<td width="816" height="61" bgcolor="#FFFFFF"><h2 align="center"><font
color="#000080" size="5"><strong><em><font
color="#FFFFFF">Online</font>Online News
</em></strong></font></h2></td>
</tr>
</table>
<center>
<p>&nbsp;</p>
<table border="1" width="300" cellspacing="0" cellpadding="0" height="1">
<!--Retrieve user ID value from session and display value-->
<tr>
<td width="50%" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#000080"><b>User Name</b></font></div></td>
<td width="50%" height="1"><div align="center"><font
color="#000080"><b><%=(String)session.getAttribute("username")%></b></
ont></div></td>
</tr>
</table>
</center>
<!--Display hyperlinks to DoLogout.jsp,MainNewsPage.jsp, and SearchNewsPage.jsp files-->
<p align="center"><a href="DoLogout.jsp">Logout</a></p>
<p align="center"><a href="SearchNewsPage.jsp">Search news </a></p>
<p align="center"><a href="MainNewsPage.jsp">Todays headlines</a></p>
<center>
<center>
<table border="1" width="48%" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" bgcolor="#FFFFFF"><div align="center"><font
color="#FF0000"><b>Headlines</b></font></div></td>
</tr>
<!--Use taglib directive to include JSTL core and XML tags-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml"
prefix="x" %>
<%
/*Retrieve hidden field value passed from SerachNewsPage.jsp*/
String tempaction = request.getParameter("txtaction");
if(tempaction.equals("bycategory"))
{
   /*For end user search by category*/
   %>
   <!--If newslist variable is empty, parse newslist.xml file and store result in newslist
   variable in application scope-->
   <c:if test="${empty applicationScope.newslist}">
   <c:import url="http://localhost:8080/news/xml/newslist.xml" var="xml"/>
   <x:parse doc="${xml}" var="newslist" scope="application"/>
   </c:if>
   <!--Store category values of all news in heading variable-->
   <x:forEach var="heading" select="$newslist/newslist/*">
   <c:set var="tempcategory" scope="request">
   <x:out select="$heading/category"/>
   </c:set>
   /*Check heading variable with end user specified category retrieved using request object*/
 <%if(((String)request.getAttribute("tempcategory")).equals((String)request.getParameter("txtcategory")))
   {
      /*For matching caegories, display headines*/
      %>
      <tr>
      <td width="100%"><center><a href="NewsDetailPage.jsp?id=<x:out
      select="$heading/@id"/>"><x:out
      select="$heading/heading"/></center></a></td>
      </tr>
      <%
   }
   %>
   </x:forEach>
   <%
}
if(tempaction.equals("bykeyword"))
{
   /*For end user search by category*/
   %>
   <!--If newslist variable is empty, parse newslist.xml file and store result in newslist
   variable in application scope-->
   <c:if test="${empty applicationScope.newslist}">
   <c:import url="http://localhost:8080/news/xml/newslist.xml" var="xml"/>
   <x:parse doc="${xml}" var="newslist" scope="application"/>
   </c:if>
   <!--Store news content in temptext variable in request scope-->
   <x:forEach var="heading" select="$newslist/newslist/*">
   <c:set var="temptext" scope="request">
   <x:out select="$heading/main"/>
   </c:set>
   <%
   /*Retrieve end user specified keyword*/
   String tempkeyword=(String)request.getParameter("txtkeyword");
   /*Retrieve news content stored in temptext variable using request object*/
   String temptext=(String)request.getAttribute("temptext");
   /*Check whether keyword exists in content*/
   if(temptext.indexOf(tempkeyword)!=-1)
   {
      /*If keyword exists in content, display heading of news as hyperlink to
      NewsDetailPage.jsp*/
      %>
      <tr>
      <td width="100%"><center><a href="NewsDetailPage.jsp?id=<x:out
      select="$heading/@id"/>"><x:out
      select="$heading/heading"/></center></a></td>
      </tr>
      <%
   }
   %>
   </x:forEach>
   <%
}
if(tempaction.equals("bydate"))
{
   /*For end user search by date*/
   %>
   <!--If newslist variable is empty, parse newslist.xml file and store result in newslist
   variable in application scope-->
   <c:if test="${empty applicationScope.newslist}" >
   <c:import url="http://localhost:8080/news/xml/newslist.xml" var="xml"/>
   <x:parse doc="${xml}" var="newslist" scope="application"/>
   </c:if>
   <!--Store news date in tempdate variable in request scope-->
   <x:forEach var="heading" select="$newslist/newslist/*">
   <c:set var="tempdate" scope="request">
   <x:out select="$heading/date"/>
   </c:set>
   <%
   /*Retrieve end user specified date*/
   String tempdate=(String)request.getParameter("txtdate");
   /*Retrieve date stored in tempdate variable*/
   String tempnewsdate=(String)request.getAttribute("tempdate");
   if(tempdate.equals(tempnewsdate))
   {
      /*If date matches, display heading of news as hyperlink to NewsDetailPage.jsp*/
      %>
      <tr>
      <td width="100%"><center><a href="NewsDetailPage.jsp?id=<x:out
      select="$heading/@id"/>"><x:out
      select="$heading/heading"/></center></a></td>
      </tr>
      <%
   }
   %>
   </x:forEach>
   <%
}
%>
</table>
</center>
</body>
</html>
End example

Download this listing.

The above code creates the DoSearchNews JSP page. The code uses the request object to obtain the criteria for search. For the search criteria category, the code uses the <x:parse> tag to parse the newslist XML document. For each news element of the XML document, the <c:set> tag stores the category value in the tempcategory variable. The code compares the value of the tempcategory variable with the end user specified category. For matching categories, the code displays a hyperlink to the NewsDetailPage.jsp file. The <x:out select="$heading/@id"/> tag sets the news ID as a query string parameter of the hyperlink. The <x:out select="$heading/heading"/> tag displays the news headline as the text of the hyperlink. The code compares the keyword and date search values with the values of the XML document and displays the headlines of matching news in the form of hyperlinks.

Figure 6-6 shows the user interface of the DoSearchNews JSP page:

Click To expand: This figure shows the user interface of the DoSearchNews JSP page that displays headlines of news that match the search criteria specified by an end user.
Figure 6-6: The DoSearchNews JSP Page


Unit Testing

The online news application is deployed and tested on the Sun Java System Application Server Platform Edition 8. The Sun Java System Application Server Platform Edition 8 contains the JSTL tag libraries that the online news application uses. You can download the application server from:

http://java.sun.com/j2ee/1.4/download.html

Note

To install the Sun Java System Application Server Platform Edition 8, you need to install Java 2 Standard Edition (J2SE) 1.4.2 on the computer.

To deploy the online news application:

  1. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Start Default Server from the Start menu to start the application server.

  2. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Deploytool from the Start menu to open the Deployment Tool window.

  3. Select New->Application from the File menu of the Deployment Tool window. The New Application dialog box appears.

  4. Click Browse in the New Application dialog box to display another New Application dialog box.

  5. Select the directory where you want to save the .ear file in the Look In combo box.

  6. Enter the name of the .ear file as OnlineNewsApp in the File Name text box, as shown in Figure 6-7:

    Click To expand: This figure shows the New Application dialog box in which you can specify the name of the application file and the location to store the file.
    Figure 6-7: The New Application Dialog Box

  7. Click the New Application button to return to the previous New Application dialog box.

  8. Click OK to create the new application.

  9. Select New->Web Component from the File menu of the Deployment Tool window. The New Web Application Wizard-Introduction dialog box appears.

  10. Click Next. The New Web Application Wizard-WAR File dialog box appears.

  11. In the New Web Application Wizard-WAR File dialog box, click Edit Contents. The Edit Contents of WebApp dialog box appears.

  12. Select all the JSP files and click Add. Select the xml directory and click Add to add the XML files. The Contents of WebApp pane of the Edit Contents of WebApp dialog box displays the added files, as shown in Figure 6-8:

    Click To expand: This figure shows the Edit Contents of WebApp dialog box that displays the files of the online music store application.
    Figure 6-8: The Edit Contents of WebApp Dialog Box

  13. Click OK to add the files to the Web application Web Archive (WAR) file.

  14. In the New Web Application Wizard-WAR File dialog box, click Next. The New Web Application Wizard-Choose Component Type dialog box appears.

  15. Select the JSP Page radio button and click Next. The New Web Application Wizard- Component General Properties dialog box appears.

  16. Select MainPage.jsp from the JSP Filename drop-down list. The remaining fields are automatically filled with values. Figure 6-9 shows the New Web Application Wizard Component General Properties dialog box:

    Click To expand: This figure shows the New Web Application Wizard Component General Properties dialog box in which you select the main page of your application.
    Figure 6-9: The New Web Application Wizard- Component General Properties Dialog Box

  17. Click Finish.

  18. In the Deployment Tool window, specify/news as the context root of your application in the Context Root text field, as shown in Figure 6-10:

    Click To expand: This figure shows the Context Root text field of the Deployment Tool window in which you can specify the context root of your application.
    Figure 6-10: The Deployment Tool Window

  19. Select Save from the File menu of the Deployment Tool window to save the application.

  20. Select Deploy from the Tools menu. The Deploy Module OnlineNewsApp dialog box appears.

  21. Specify the application server user name and password in the User Name and Password fields and then click OK. The Distribute Module dialog box appears and indicates the successful deployment of the application.

After deploying the application, you can test the application. To test the application:

  1. Type the following URL in the address bar of the browser:

    http://localhost:8080/news/MainPage.jsp

  2. The MainPage JSP page appears and displays headlines of news. Specify Peter in the User ID field and peter in the Password field, as shown in Figure 6-11:

    Click To expand: This figure shows the MainPage JSP page that displays the fields in which you can specify the user ID and password to log on and view the news.
    Figure 6-11: The MainPage JSP Page

  3. Click the Logon button. The MainNewsPage JSP page displays the news headlines as hyperlinks. Figure 6-12 shows the headlines displayed as hyperlinks in the MainNewsPage JSP page:

    Click To expand: This figure shows the headlines of news as hyperlinks along with the Logout and Search news hyperlinks.
    Figure 6-12: The MainNews JSP Page

  4. Select a headline to view the complete news. The NewsDetailPage JSP page displays the complete news, as shown in Figure 6-13:

    Click To expand: This figure shows the NewsDetailPage JSP page that displays the complete news along with the Logout, View headlines, and Search news hyperlinks.
    Figure 6-13: The NewsDetailPage JSP Page

  5. Select the Search news hyperlink. The SearchNewsPage JSP page displays the fields to allow an end user to search for news. Specify a keyword in the Keyword text field to search for news that contains the specified keyword, as shown in Figure 6-14:

    Click To expand: This figure shows the SearchNewsPage JSP page that displays the fields in which you can specify the category, keyword, or date to search for news.
    Figure 6-14: The SearchNewsPage JSP Page

  6. Click the Search button of the Keyword field. The DoSearchNews JSP page displays the headline of the news that matches the search criteria, as shown in Figure 6-15:

    Click To expand: This figure shows the DoSearchNews JSP page that displays the headline of the news that contains the specified keyword.
    Figure 6-15: The DoSearchNews JSP Page

  7. Select the hyperlink to view the content of the news.

  8. Select the Logout hyperlink to log out from the application.


Point 7: Creating an Internationalized Application Using JSP and XML

You can integrate JSP with XML to develop internationalized applications. An internationalized application supports multiple languages, such as US English, French, and Spanish. You can localize an internationalized application to support a particular language. To implement localization, the internationalized application can use XML files that store country-specific data.

This chapter describes how to create an internationalized online discussion forum that supports US English and French. When an end user selects a particular country name in the home page, the application displays its corresponding user interface.

Requirements of the Online Discussion Forum Application

To access the US English or French user interface, end users need to log on to the online discussion forum. In the user interface, end users can select a specific discussion category to view the existing discussions or start a new discussion under an existing or new topic. The application contains various XML files that store data on end user logon, discussions, and localization.

The XML files of the online discussion forum application are:

  • userlist.xml: Stores end user logon information.

  • discussionlist.xml: Stores information about a discussion topic, sub topic, and content.

  • uslist.xml: Stores user interface text in US English.

  • francelist.xml: Stores user interface text in French.

The JSP pages of the online discussion forum application are:

  • Index.jsp: Displays options to select a country. This is the home page of the application.

  • Logon.jsp: Displays fields to accept end user logon information. This is the logon page of the application.

  • DoLogon.jsp: Accesses the userlist.xml file to authenticate end users.

  • DoLogout.jsp: Invalidates the current session and forwards the request to the home page.

  • UserPage.jsp: Displays the link to view and start discussions.

  • AddDiscussion.jsp: Allows an end user to start a new discussion.

  • ViewDiscussion.jsp: Allows an end user to view the existing discussions.

The JSP pages of the application use the following Java classes to allow the end user to access the application in US English or French:

  • LanguageDocParser.java: Parses the XML documents that contain localized data to retrieve the data.

  • DisplayString.java: Uses an object of the LanguageDocParser class to provide language-specific data to the JSP pages to create a localized user interface.

Figure 7-1 shows the architecture of the online discussion forum application:

Click To expand: This figure shows the JSP files of the online discussion forum application and the sequence in which they are used.
Figure 7-1: Architecture of the Online Discussion Forum Application


Creating the XML Files to Store Application Data

The userlist.xml and discussionlist.xml files of the online discussion forum application store logon information of end users and contents of discussions.

Listing 7-1 shows the content of the userlist.xml file:

Listing 7-1: The userlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<userlist>
<user name="Peter" password="peter">
</user>
<user name="Sara" password="sara">
</user>
</userlist>
End example

Download this listing.

The above code creates the userlist.xml file that contains end user logon information. The code uses the userlist root element to enclose user elements. A user element contains the name and password attributes that store the user ID and password of an end user.

The discussionlist.xml file uses the discussionlist root element. Listing 7-2 shows the content of the discussionlist.xml file:

Listing 7-2: The discussionlist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<DiscussionList>
<query Category="Programming language" Discussion="Sun has recently released the Sun Java
System Application Server. You can download the server from the Sun Web site."
SubCategory="J2EE" user="Peter">
</query>
<query Category="Operating Systems" Discussion="Can anyone help me on how Linux kernel
versioning works? " SubCategory="Linux" user="Peter">
</query>
</DiscussionList>
End example

Download this listing.

The above code creates the discussionlist.xml file that contains two discussion entries. Each discussion entry is represented by a query element, which is enclosed within the DiscussionList root element. Each query element contains the Category, Discussion, SubCategory, and user attributes.


Creating the XML Files to Store Country-Specific Data

The uslist.xml and francelist.xml files store text specific to US and France. This text is displayed in the user interface of the application.

Listing 7-3 shows the content of the uslist.xml file:

Listing 7-3: The uslist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<wordlist>
<word name="heading">
Online Discussion Forum
</word>
<word name="error">
Invalid Logon Information
</word>
<word name="userLogon">
User ID
</word>
<word name="password">
Password
</word>
<word name="submit">
Submit
</word>
<word name="reset">
Reset
</word>
<word name="heading1">
Welcome to the discussion forum
</word>
<word name="user">
User ID
</word>
<word name="logout">
Logout
</word>
<word name="goMain">
Go to main page
</word>
<word name="useroption">
User Options
</word>
<word name="newdiscussion">
Start a new discussion
</word>
<word name="viewdiscussion">
View discussion
</word>
<word name="postnewquery">
Post Message
</word>
<word name="category">
Topic
</word>
<word name="subcategory">
Sub Topic
</word>
<word name="discussion">
Discussion
</word>
<word name="submitquery">
Submit Query
</word>
<word name="querylist">
View Discussion
</word>
<word name="existingdiscussion">
Existing Discussions
</word>
</wordlist>
End example

Download this listing.

The above code creates the uslist.xml file. The code uses the wordlist element to enclose word elements. Each word element has a name attribute. The name attribute value specifies a key that identifies the country-specific content enclosed by the word element. The application file uses this key to retrieve the country-specific content.

The structure of the francelist.xml file is similar to that of the uslist.xml file. The francelist.xml stores the content of the word elements in French. Listing 7-4 shows the content of the francelist.xml file:

Listing 7-4: The francelist.xml File
Start example
<?xml version="1.0" encoding="UTF-8"?>
<wordlist>
<word name="heading">
Le Forum en ligne de Discussion
</word>
<word name="error">
L'information n'est pas valide.
</word>
<word name="userLogon">
ID de Utilisateur
</word>
<word name="password">
Mot de passé
</word>
<word name="submit">
Soumettre
</word>
<word name="reset">
Remet a l etat initial
</word>
<word name="heading1">
Accueillir au forum de discussion
</word>
<word name="user">
ID de Utilisateur
</word>
<word name="logout">
Sortie du systeme
</word>
<word name="goMain">
Aller a la page principale
</word>
<word name="useroption">
Options d'utilisateur
</word>
<word name="newdiscussion">
Commencer une nouvelle discussion
</word>
<word name="viewdiscussion">
Regarder la discussion
</word>
<word name="postnewquery">
Commencer la Discussion
</word>
<word name="category">
Categorie
</word>
<word name="subcategory">
Sous la Categorie
</word>
<word name="discussion">
Discussion
</word>
<word name="submitquery">
Soumettre la Question
</word>
<word name="querylist">
Regarder la Discussion
</word>
<word name="existingdiscussion">
Discussions existantes
</word>
</wordlist>
End example

Download this listing.


Creating the Utility Classes

The online discussion forum application uses the DisplayString and LanguageDocParser classes to retrieve country-specific data from the uslist.xml and francelist.xml files. The LanguageDocParser class uses Simple API for XML (SAX) to serially parse the XML document from the start to the end. The LanguageDocParser class implements the call back handler methods to retrieve country-specific content that corresponds to a key specified as the name attribute in the XML documents. The parser calls the call back handler methods when it encounters various components of the XML document, such as start tag, text, and end tag, while parsing the document.

Listing 7-5 shows the content of the LanguageDocParser.java file:

Listing 7-5: The LanguageDocParser.java File
Start example
package TxtConverter;
/*Import the necessary packages*/
import java.io.*;
import java.net.*;
import java.util.Properties;
/*Defines all the interfaces for the SAX parser*/
import org.xml.sax.*;
/*Defines the class that will handle the SAX events*/
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
/*Throws an exception if the application is unable to produce a parser that matches the configuration option*/
import javax.xml.parsers.ParserConfigurationException;
/*Parses XML document*/
import javax.xml.parsers.SAXParser;
public class LanguageDocParser extends DefaultHandler
/*Implementing the contentHandler interface by extending DefaultHanlder defined in org.xml.sax.helpers package*/
{
   String langpath;
   static String result="";
   static String convert;
   boolean flag=false;
   /*Implement default constructor*/
   public LanguageDocParser()
   {}
   /*Implement constructor that accepts a String value of the property file key and an XML document
   attribute whose value needs to be retrieved*/
   public LanguageDocParser(String fileName, String att)
   {
      try
      {
         convert=att;
         /*Create a URL object to load properties file*/
         URL url=new URL("http://127.0.0.1:8080/seven/path.properties");
         /*Open URL connection*/
         URLConnection ucon=url.openConnection();
         /*Retrieve the property value*/
         Properties prop = new Properties();
         prop.load(ucon.getInputStream());
         langpath = prop.getProperty(fileName);
      }
      catch(Exception ex)
      {
         ex.printStackTrace();
      }
      DefaultHandler defaultHandler = new LanguageDocParser();
      /*Creating an instance of SAXParserFactory class*/
      SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
      try
      {
         /*Obtain the parser represented by the SAXParser object*/
         SAXParser Sax_Parser = saxParserFactory.newSAXParser();
         /*Parse the XML file*/
         Sax_Parser.parse( new FileInputStream(langpath), defaultHandler);
      }
      catch (Throwable thr)
      {
         thr.printStackTrace();
      }
   }
   /*Implement the call back method that handles the start document event notification*/
   public void startDocument() throws SAXException
   {
   }
   /*Implement the call back method that handles the end document event notification*/
   public void endDocument() throws SAXException
   {
   }
   /*Implement the call back method that handles the start element event notification*/
   public void startElement(String namespaceURI, String sName, String qName, Attributes attrs)
   throws SAXException
   {
   try
   {
      /*Check if Attributes object is null*/
      if(attrs.getValue(0)!=null)
      {
         /*Retrieve the attribute value of the element*/
         String str=attrs.getValue(0);
          if (LanguageDocParser.convert.equals(str))
              {
                  /*If attribute value matches with value stored in convert, set flag to true*/
                   flag=true;
              }
             else
             {
                 flag=false;
             }
         }
      }
   catch(Exception ex)
    {
       ex.printStackTrace();
    }
   }
   /*Implement the call back method that handles the end element event notification*/
   public void endElement(String namespaceURI, String sName, String qName) throws SAXException
   {
   /*Set flag to false*/
   flag=false;
   }
   /*Method that handles the character data event*/
   public void characters(char buf[], int start, int len) throws SAXException/*For handling character event.*/
   {
      if (flag==true)
      /*If flag is true, convert the char[] that contains the XML element characters to String*/
      {
         LanguageDocParser.result="";
         for (int i = start; i < start+len; i++)
         {
            LanguageDocParser.result+=new String(new Character(buf[i]).toString());
         }
      }
   }
   public String getXMLContentResult()
   {
      /*Return the attribute value*/
      return LanguageDocParser.result;
   }
}
End example

Download this listing.

The above code creates the LanguageDocParser.java file. The constructor of the LanguageDocParser class accepts two String arguments to initialize the class. The first argument is a String value that represents the XML document that contains country-specific data. The second argument is a String value that represents an attribute of the XML document that stores country-specific data. In the constructor of the LanguageDocParser class, the code obtains a SAXParser object by calling the newSAXParser() method of the SAXParserFactory class. The parse() method of the SAXParser object parses the XML document that stores country-specific data. The code overrides the call back methods of the DefaultHandler interface to receive notification about parsing events. In the doStartElement() call back method, the code sets the value of a boolean variable flag to true when the parser encounters an attribute, which is passed as the constructor argument, in the XML document. In the characters() call back method, the code retrieves the content of the element whose attribute matches the value that is passed as an argument to the constructor. The getXMLContentResult() method returns the country-specific content of the XML element.

The DisplayString class of the online discussion forum uses the LanguageDocParser class to obtain country-specific content. The class implements various methods, depending on the requirements of the user interfaces. For example, to display the password field label, the DisplayString class implements the getPassword() method. The JSP page that provides the user interface of the Logon page calls the getPassword() method to display the label of the password field.

Listing 7-6 shows the content of the DisplayString.java file:

Listing 7-6: The DisplayString.java File
Start example
package TxtConverter;
/*Utility class to access resource bundle*/
import java.util.*;
import TxtConverter.*;
public class DisplayString
{
   String fileName;
   /*Public default constructor*/
   public DisplayString()
   {
   }
   /*Constructor that accepts the property file key to the path of XML document*/
   public DisplayString(String lang)
   {
      if (lang.equals("1"))
      {
      /*For end users of US, set filename value to uslistpath*/
      fileName="uslistpath";
      }
      else if (lang.equals("2"))
      {
      /*For end users of French, set filename value to francelistpath*/
      fileName="francelistpath";
      }
   }
   public String getString(String name)
   {
      /*Create an object of LanguageDocParser passing the property
      file key value and name of the attribute of XML file to translate*/
      LanguageDocParser langParser=new LanguageDocParser(fileName,name);
      /*Call getXMLContentResult() and return the translated result as String*/
      return langParser.getXMLContentResult();
   }
   /*Retrieves value of heading attribute of XML document*/
   public String getHeading()
   {
      String rs=getString("heading");
      return rs;
   }
   /*Retrieves value of userLogon attribute of XML document*/
   public String getUserLogon()
   {
      return getString("userLogon");
   }
   /*Retrieves value of password attribute of XML document*/
   public String getPassword()
   {
      return getString("password");
   }
   /*Retrieves value of error attribute of XML document*/
   public String getError()
   {
      return getString("error");
   }
   /*Retrieves value of submit attribute of XML document*/
   public String getSubmit()
   {
      return getString("submit");
   }
   /*Retrieves value of reset attribute of XML document*/
   public String getReset()
   {
      return getString("reset");
   }
   /*Retrieves value of heading1 attribute of XML document*/
   public String getHeading1()
   {
      return getString("heading1");
   }
   /*Retrieves value of logout attribute of XML document*/
   public String getLogout()
   {
   return getString("logout");
   }
   /*Retrieves value of goMain attribute of XML document*/
   public String getGoMain()
   {
      return getString("goMain");
   }
   /*Retrieves value of user attribute of XML document*/
   public String getUser()
   {
   return getString("user");
   }
   /*Retrieves value of useroption attribute of XML document*/
   public String getUserOption()
   {
      return getString("useroption");
   }
   /*Retrieves value of newdiscussion attribute of XML document*/
   public String getNewDiscussion()
   {
      return getString("newdiscussion");
   }
   /*Retrieves value of viewdiscussion attribute of XML document*/
   public String getViewDiscussion()
   {
      return getString("viewdiscussion");
   }
   /*Retrieves value of postnewquery attribute of XML document*/
   public String getPostNewQuery()
   {
      return getString("postnewquery");
   }
   /*Retrieves value of category attribute of XML document*/
   public String getCategory()
   {
      return getString("category");
   }
   /*Retrieves value of subcategory attribute of XML document*/
   public String getSubCategory()
   {
      return getString("subcategory");
   }
   /*Retrieves value of discussion attribute of XML document*/
   public String getDiscussion()
   {
      return getString("discussion");
   }
   /*Retrieves value of submitquery attribute of XML document*/
   public String getSubmitQuery()
   {
      return getString("submitquery");
   }
   /*Retrieves value of existingdiscussion attribute of XML document*/
   public String getExistingDiscussion()
   {
      return getString("existingdiscussion");
   }
   /*Retrieves value of querylist attribute of XML document*/
   public String getQueryList()
   {
      return getString("querylist");
   }
}
End example

Download this listing.

The above code creates the DisplayString class. The constructor of this class accepts a String argument that specifies the country of an end user. In the constructor, the filename variable specifies the path of the XML file to parse. The getString() method creates an object of the LanguageDocParser class. In the getString() method, the code calls the getXMLContentResult() method of the LanguageDocParser class. The code implements various methods, such as getHeading(), getPassword(), and getQueryList(), which use the getString() method to return values for the user interface text.


Creating the Home Page

In the home page of the online discussion forum application, end users can select a country name, US or France, to access the application in US English or French. The Index JSP provides the home page of the application.

Listing 7-7 shows the content of the Index.jsp file:

Listing 7-7: The Index.jsp File
Start example
<html>
<head>
<style type="text/css">
</style>
</head>
<body text="#000000">
<div align="center">
<h1 class="style1"><font color="#E24907">Online Discussion Forum</font></h1>
<p class="style4 style2"><em><strong>Select your country to enter discussion
forum </strong></em></p>
<table width="75%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="4%">&nbsp;</td>
<td width="4%">&nbsp;</td>
<td width="39%">&nbsp;</td>
<td width="13%">&nbsp;</td>
<td width="40%"><div align="center" class="style3">
<p align="left">&nbsp;</p>
<p>&nbsp;</p>
</div></td>
</tr>
<!--Display US flag and hyperlink to Logon.jsp with value of query parameter lang as 1-->
<tr>
<td width="4%">&nbsp;</td>
<td width="4%">&nbsp;</td>
<td width="39%"><div align="right"><a href="logon.jsp?lang=1"><img
src="us.jpg" width="84" height="57"></a></div></td>
<td width="13%">&nbsp;</td>
<td width="40%" height="23"><div align="left"><a href="Logon.jsp?lang=1">
United States </a></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td height="23">&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td height="23">&nbsp;</td>
</tr>
<!--Display France flag and hyperlink to Logon.jsp with value of query parameter lang as 2-->
<tr>
<td width="4%">&nbsp;</td>
<td width="4%">&nbsp;</td>
<td width="39%"><div align="right"><img src="france.jpg" width="87"
height="51"></div></td>
<td width="13%">&nbsp;</td>
<td width="40%" height="23"><div align="left"><a
href="Logon.jsp?lang=2">France</a></div></td>
</tr>
</table>
<p>&nbsp;</p><p><font size="3"></font></p>
<p>&nbsp; </p>
<p></p>
<p></p>
</div>
</body>
</html>
End example

Download this listing.

The above code displays the United States and France hyperlinks. The United States hyperlink specifies Logon.jsp as the URL. The URL contains a query parameter, lang, with value 1. The France hyperlink specifies Logon.jsp as the URL. The URL contains a query parameter, lang, with value 2.

Figure 7-2 shows the home page of the online discussion forum application:

Click To expand: This figure shows the home page of the online discussion forum application that displays the United States and France hyperlinks along with images of their flags.
Figure 7-2: The Home Page


Creating the Logon Module

The logon module of the online discussion forum application helps authenticate the user ID and password of the end user. This module contains three files: Logon.jsp, DoLogon.jsp, and DoLogout.jsp.

Creating the Logon.jsp File

The Logon.jsp file provides the user interface of the logon page, based on the country the end user selects. The logon page displays the fields to accept the user ID and password of an end user.

Listing 7-8 shows the content of the Logon.jsp file:

Listing 7-8: The Logon.jsp File
Start example
<%@page import="TxtConverter.*"%>
<%
String error=request.getParameter("error");
/*Call the constructor of DisplayString by passing the value of query parameter, lang*/
DisplayString ds=new DisplayString(request.getParameter("lang"));
/*Store request query parameter value to session*/
session.setAttribute("lang1",request.getParameter("lang"));
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
</style>
</head>
<body text="#000000">
<div align="center">
<!--Display heading using the DisplayString utility class-->
<h1 class="style1"><font color="#E24907"><%= ds.getHeading()%></font> </h1>
<%
if("error".equals(error))
{
   /*Display error message using the DisplayString utility class for authentication error*/
   %>
   <p><font size="3"><b><font color="#E24907"><%=
   ds.getError()%></font></b></font></p>
   <%
}
%>
<form name="form1" method="post" action="DoLogon.jsp">
<table width="46%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="16%">&nbsp;</td>
<!--Display user ID label using resource bundle-->
<td width="35%">
<div align="left"><font size="3"><%=
ds.getUserLogon()%></font></div>
</td>
<td width="32%"><font size="3">
<input type="text" name="textfield_logon"/>
</font></td>
<td width="17%">&nbsp;</td>
</tr>
<tr>
<!--Display Password label from resource bundle-->
<td width="16%" height="45">&nbsp;</td>
<td width="35%" height="45">
<div align="left"><%= ds.getPassword()%>&nbsp;&nbsp;&nbsp;</div>
</td>
<td width="32%" height="45">
<input type="password" name="textfield_password"/>
</td>
<td width="17%" height="45">&nbsp;</td>
</tr>
<tr>
<td width="16%">&nbsp;</td>
<td width="35%">
<div align="right">
<!--Display Submit button label from resource bundle-->
<input type="submit" name="Submit" value=<%= ds.getSubmit()%> class="button"/>
</div>
</td>
<td width="32%">
<div align="left">
<!--Display Reset button label from resource bundle-->
<input type="reset" name="Reset" value=<%= ds.getReset()%> class="button"/>
</div>
</td>
<td width="17%">&nbsp;</td>
</tr>
</table>
</form>
<p>&nbsp;</p><p><font size="3"></font></p>
<p>&nbsp;</p>
<p></p>
<p></p>
</div>
</body>
</html>
End example

Download this listing.

The above code stores the request query parameter, lang1, to the session object. This code passes the value of the query parameter to the constructor of the DisplayString class. The code then uses the DisplayString object to call the methods of the DisplayString class to display the user interface text.

Figure 7-3 shows the user interface of the Logon.jsp file for US:

Click To expand: This figure shows the user interface the Logon.jsp file displays for US.
Figure 7-3: User Interface of Logon.jsp File for US

Figure 7-4 shows the user interface of the Logon.jsp file for France:

Click To expand: This figure shows the user interface the Logon.jsp file displays for France.
Figure 7-4: User Interface of Logon.jsp File for France

Creating the DoLogon.jsp and DoLogout.jsp Files

The DoLogon.jsp file authenticates end user information using data stored in the userlist.xml file. After authentication, the DoLogon.jsp file displays a country-specific user interface, based on the country an end user selects. The user interface displays a hyperlink that an end user can select to view the User page of the application.

Listing 7-9 shows the content of the DoLogon.jsp file:

Listing 7-9: The DoLogon.jsp File
Start example
<%@page import="TxtConverter.*"%>
<%
/*Call the constructor of DisplayString by passing the value of query parameter, lang*/
DisplayString ds=new DisplayString((session.getAttribute("lang1")).toString());
%>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Online Discussion Forum</title>
</head>
<body>
<p>
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, org.w3c.dom.*, java.net.*,java.util.*"%>
<%!String userpath;%>
<%
try
{
   /*Create a URL object to load properties file*/
   URL url=new URL("http://127.0.0.1:8080/seven/path.properties");
   /*Open URL connection*/
   URLConnection ucon=url.openConnection();
   /*Retrieve the userlistpath property*/
   Properties prop = new Properties();
   prop.load(ucon.getInputStream());
   userpath = prop.getProperty("userlistpath");
}
catch(Exception ex)
{
   ex.printStackTrace();
}
/*Retrieve user ID and password from request object*/
String userid=request.getParameter("textfield_logon");
String password=request.getParameter("textfield_password");
/*Obtain a DocumentBuilder object by calling the newInstance()method*/
DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
/*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
DocumentBuilder docb = docbfact.newDocumentBuilder();
/*Parse the userlist XML document*/
Document doc = docb.parse(new FileInputStream(userpath));
String tempuser,temppassword;
NamedNodeMap nnp;
Node n;
boolean success = false;
tempuser="";
temppassword="";
/*Obtain a NodeList object that contains nodes corresponding to the user elements*/
NodeList nodelist1 = doc.getElementsByTagName("user");
/*Iterate through the NodelList object*/
for(int int_1=0;int_1 < nodelist1.getLength(); int_1 ++)
{
   /*Retrieve values of name and password attributes from nodes*/
   nnp=(nodelist1.item(int_1)).getAttributes();
   n=nnp.getNamedItem("name");
   tempuser=(n.getNodeValue());
   n=nnp.getNamedItem("password");
   temppassword =(n.getNodeValue());
   /*Compare name and password attributes of nodes with end user specified name and password*/
   if(tempuser.equals(userid) && temppassword.equals(password))
   {
      success=true;
   }
}
/*Store query parameter value to session*/
session.setAttribute("lang",request.getParameter("lang"));
if (success==true)
{
   /*If authentication succeeds, store user ID to session*/
   session.setAttribute("userid",userid);
   %> </p>
   <p>  <Center>
   <h1 class="style1"><font color="#E24907"><%= ds.getHeading()%></font> </h1>
   <br><br>
   <b><font color="#800000"><%= ds.getHeading1()%></font></b>
   </Center>
   </p>
   <div align="justify">
   <table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
   left: 365px; top: 204px; width: 225px">
   <tr>
   <td height="18" bgcolor="#FFFFFF"><div align="center"><font
   color="#FFFFFF"><b><a href="DoLogout.jsp"><%=
   ds.getLogout()%></a></b></font></div></td>
   </tr>
   <tr>
   <td height="18" bgcolor="#FFFFFF"><div align="center"><b>
   <!--Call getGoMain() method of Display String to display country specific message-->
   <a href="UserPage.jsp">
   <%= ds.getGoMain()%></a></b></div></td>
   </tr>
   </table>
   </div>
   </body>
   </html>
   <%
}
else
{
   /*For authentication error, display hyperlink to Index.jsp*/
   %>
   <center><p><font size="3"><b><font color="#E24907"><%=
   ds.getError()%></font> </b></font></p></Center>
   <center><font color="#FFFFFF"><b><a href="Index.jsp"><%=
   ds.getGoMain()%></a></b></font></center>
   <%
}
%>
End example

Download this listing.

The above code creates the DoLogon.jsp file. This code obtains the value of the query parameter, lang1, which is stored in session to call the constructor of the DisplayString class. A DocumentBuilder object parses the userlist XML document using the parse() method. The parse() method returns a Document object that represents an object tree of the XML document. The code navigates the object tree to compare the user ID and password values of an end user with those stored in the object tree node. When the user ID and password values match, the code calls the methods of the DisplayString class to display the country-specific user interface. If authentication fails, the code displays a country-specific error message.

Figure 7-5 shows the user interface of the DoLogon JSP for US that appears after authentication:

Click To expand: This figure shows the user interface of the DoLogon JSP for US. The interface also contains the Logout and Go to main page hyperlinks.
Figure 7-5: User Interface of DoLogon JSP for US on Successful Authentication

Figure 7-6 shows the user interface of the DoLogon JSP for France when authentication fails:

Click To expand: This figure shows the user interface of the DoLogon JSP for France that displays an error message in French to indicate logon failure.
Figure 7-6: User Interface of DoLogon JSP for France on Unsuccessful Authentication

The DoLogout.jsp file of the online message board application, when called, invalidates the current session and forwards the request to the Index JSP page. The following code shows the content of the DoLogout.jsp file:

<%
/*Invalidate current session*/
session.setAttribute("userid","");
session.invalidate();
%>
<!--Forward request to Index.jsp-->
<jsp:forward page="Index.jsp"/>


Creating the User Module

The user module of the online discussion forum application allows end users to view and post discussions. The user module contains three files: UserPage.jsp, AddDiscussion.jsp, and ViewDiscussion.jsp.

Creating the UserPage.jsp File

The UserPage.jsp file of the application provides links that allow an end user to post a new discussion or view the existing discussion topics.

Listing 7-10 shows the content of the UserPage.jsp file:

Listing 7-10: The UserPage.jsp File
Start example
<%@page import="TxtConverter.*"%>
<%
/*Call the constructor of DisplayString by passing the value of query parameter, lang*/
DisplayString ds=new DisplayString((session.getAttribute("lang1")).toString());
%>
<html>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>User Options</title>
</head>
<body>
<!--Display banner heading using getHeading() method of DisplayString class-->
<center><h1 class="style1"><span class="style1"><font
color="#E24907"><%= ds.getHeading()%></font> </h1></center>
<p>&nbsp;</p>
<!--Display page name using getUserOption() method of DisplayString class-->
<p align="center"><b><font face="Arial" size="5" color="#0000FF"><%=
ds.getUserOption() %> </font></b></p>
<table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<!--Display user ID label using getUser() method of DisplayString class-->
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#FF0000"><b><%= ds.getUser() %>
</b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1">
<div align="left"></div>
<!--Display user ID value from session-->
<div align="center"><font
color="#FF0000"><%=session.getAttribute("userid")%></font></div></td>
</tr>
</table>
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute; left: 653px; top: 128px;
width: 259px" >
<tr>
<!--Display logout hyperlink-->
<td height="18" bgcolor="#FFFFFF"><div align="center"><font
color="#FFFFFF"><b><a href="DoLogout.jsp"><%=
ds.getLogout()%></a></b></font></div></td>
</tr>
</table>
</div>
<p align="center">&nbsp;</p>
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="300" style="position: absolute;
left: 322px; top: 248px; width:
300">
<tr>
<!--Display text for hyperlink to AddDiscussion.jsp using getNewDiscussion() method of
DisplayString class-->
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="AddDiscussion.jsp"><%= ds.getNewDiscussion() %>
</a></b></i></div></td>
</tr>
<tr>
<!--Display text for hyperlink to ViewDiscussion.jsp using getViewDiscussion() method of
DisplayString class-->
<td bgcolor="#FFFFFF"><div align="center"><i><b><a
href="ViewDiscussion.jsp"><%= ds.getViewDiscussion()%>
</a></b></i></div></td>
</tr>
</table>
</div>
</body>
</html>
End example

Download this listing.

The above code creates the UserPage.jsp file. This code retrieves the value of the String, lang1, which represents an end user country stored in session, to create an object of the DisplayString class. The code calls the methods of the DisplayString class to provide the user interface. The user interface displays hyperlinks to access the AddDiscussion.jsp and ViewDiscussion.jsp files.

Figure 7-7 shows the user interface of the UserPage JSP in French:

Click To expand: This figure shows the user interface of the UserPage JSP in French. It displays hyperlinks to access the AddDiscussion.jsp and ViewDiscussion.jsp files.
Figure 7-7: User Interface of UserPage JSP in French

Creating the AddDiscussion.jsp File

The AddDiscussion JSP page provides fields that accept end user information about a new discussion. This information is stored in the discussionlist.xml file.

Listing 7-11 shows the content of the AddDiscussion.jsp file:

Listing 7-11: The AddDiscussion.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer, javax.xml.transform.TransformerFactory,javax.xml.
transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException,
javax.xml.transform.dom.DOMSource, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%@page import="TxtConverter.*"%>
<%!String discussionpath;%>
<%
/*Call the constructor of DisplayString by passing the value of query parameter, lang*/
DisplayString ds=new DisplayString((session.getAttribute("lang1")).toString());
%>
<html>
<%
/*Retrieve category, sub category, and discussion content from request object*/
String tempCategory, tempSubCategory,tempDiscussion,tempuser;
tempCategory=request.getParameter("txtCategory");
tempDiscussion=request.getParameter("txtDiscussion");
tempSubCategory=request.getParameter("txtSubCategory");
if(!(tempCategory == null || tempDiscussion == null ||tempSubCategory == null))
{
 try{
      /*Create a URL object to load properties file*/
      URL url=new URL("http://127.0.0.1:8080/seven/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the discussionlistpath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      discussionpath = prop.getProperty("discussionlistpath");
   }
   catch(Exception ex)
    {
     ex.printStackTrace();
    }
   /*Obtain a DocumentBuilder object by calling the newInstance()method*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the discussionlist XML document*/
   Document doc = docb.parse(new FileInputStream(discussionpath));
   /*Obtain Element object that represents the root element of an XML document*/
   Element doce = doc.getDocumentElement();
   /*Create a new child element*/
   Element newe = doc.createElement("query");
   /*Obtain user ID from session*/
   tempuser=session.getAttribute("userid").toString();
   /*Set category, sub category, discussion, and user ID values as attributes to the query Element*/
   newe.setAttribute("Category", tempCategory);
   newe.setAttribute("Discussion", tempDiscussion);
   newe.setAttribute("user",tempuser);
   newe.setAttribute("SubCategory", tempSubCategory);
   /*Append query Element to root Element*/
   doce.appendChild(newe);
   /*Obtain a TransformerFactory object*/
   TransformerFactory tFactory = TransformerFactory.newInstance();
   /*Create a Transformer object*/
   Transformer transformer = tFactory.newTransformer();
   /*Set output property of Transformer object*/
   transformer.setOutputProperty(OutputKeys.INDENT,"yes");
   /*Create a DOMSource that acts a transformation source*/
   DOMSource source = new DOMSource(doc);
   /*Create a StreamResult object that represents a stream to the XML document and acts as the
   /*destination of the transformation*/
   StreamResult result = new StreamResult(new PrintStream(new
   FileOutputStream(discussionpath)));
   /*Perform the transformation to transform the document object tree to the XML document*/
   transformer.transform(source, result);
}
%>
<!--Display banner heading using resource bundle-->
<Center><H1 class="style1"><font color="#E24907"><%=
ds.getHeading()%></font></H1></Center>
<br><br>
<p align="center"><font size="5"><b>
<!--Display page heading using resource bundle-->
<%= ds.getPostNewQuery() %></b></font>
</p>
<table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<!--Display user ID label using resource bundle-->
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#FF0000"><b><%= ds.getUser() %>
</b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1">
<!--Display user ID value from session-->
<font color="#FF0000"><b>
<%=session.getAttribute("userid")%></b></font></td>
</tr>
</table>
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 707px; top: 129px; width: 208px">
<tr>
<!--Display text of hyperlink to DoLogout.jsp using resource bundle-->
<td height="18" bgcolor="#FFFFFF"><font color="#FFFFFF"><b><a
href="DoLogout.jsp"><%= ds.getLogout() %></a></b></font></td>
</tr>
<tr>
<td height="18" bgcolor="#FFFFFF"><b>
<!--Display text of hyperlink to UserPage.jsp using resource bundle-->
<a href="UserPage.jsp">
<%= ds.getGoMain() %></a></b></td>
</tr>
</table>
</div>
<!--Display HTML form to add new discussion-->
<form action = AddDiscussion.jsp method ="post">
<div align="center">
<table width="544" border="1" cellpadding="0" cellspacing="0" bordercolor="#FF0000">
<tr>
<!--Display label for category field using resource bundle-->
<td width="194" bgcolor="#FFFFFF"><div align="center"><%= ds.getCategory()
%></div></td>
<td width="450" bgcolor="#FFFFFF">
<input name="txtCategory" size="30" >
<select name ="txtCategory1" onChange="{form.txtCategory.value=''+this.value+'';}">
<%
java.util.HashMap hmap = new HashMap();
try{
      /*Create a URL object to load properties file*/
      URL url=new URL("http://127.0.0.1:8080/seven/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the discussionlistpath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      discussionpath = prop.getProperty("discussionlistpath");
   }
   catch(Exception ex)
    {
     ex.printStackTrace();
    }
   /*Obtain a DocumentBuilder object by calling the newInstance()method*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the discussionlist XML document*/
   Document doc = docb.parse(new FileInputStream(discussionpath));
   /*Obtain query elemens of the XML document as a NodeList object*/
   NodeList nl1 = doc.getElementsByTagName("query");
   /*Iterate through the NodeList object*/
   for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
   {
      /*Obtain the Node object*/
      Node n=nl1.item(int_1);
      /*Retrieve attributes of the Node objects*/
      NamedNodeMap nnp = n.getAttributes();
      Object
 obj1=hmap.put((nnp.getNamedItem("Category")).getNodeValue(),(nnp.getNamedItem("Category")).getNodeValue());
      if(obj1==null)
      {
         %>
         <!--Populate category drop-down list with values of Category attributes-->
         <option
    value="<%=(nnp.getNamedItem("Category")).getNodeValue()%>"><%=(nnp.getNamedItem
    ("Category")).getNodeValue()%></option>
         <%
      }
   }
   %>
   </select>
   </td>
   </tr>
   <tr>
   <!--Display label for sub category field using resource bundle-->
   <td width="194" bgcolor="#FFFFFF"><div align="center"><%= ds.getSubCategory()
   %></div></td>
   <td width="450" bgcolor="#FFFFFF">
   <input name="txtSubCategory" size="30" >
   <select name ="txtSubCategory1"
   onChange="{form.txtSubCategory.value=txtSubCategory1.value;}">
   <%
   hmap = new HashMap();
   /*Obtain a DocumentBuilder object by calling the newInstance()method*/
   docbfact = DocumentBuilderFactory.newInstance();
   /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
   docb = docbfact.newDocumentBuilder();
   /*Parse the discussionlist XML document*/
   doc = docb.parse(new FileInputStream(discussionpath));
   /*Obtain query elemens of the XML document as a NodeList object*/
   nl1 = doc.getElementsByTagName("query");
   /*Iterate through the NodeList object*/
   for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
   {
      /*Obtain the Node object that represents elements of an XML document*/
      Node n=nl1.item(int_1);
      /*Retrieve attributes of the Node objects*/
      NamedNodeMap nnp = n.getAttributes();
      Object
 obj1=hmap.put((nnp.getNamedItem("SubCategory")).getNodeValue(),(nnp.getNamedItem
 ("SubCategory")).getNodeValue());
      if(obj1==null)
      {
         %>
         <!--Populate category drop-down list with values of SubCategory attributes-->
         <option
 value="<%=(nnp.getNamedItem("SubCategory")).getNodeValue()%>"><%=(nnp.getNamedItem
 ("SubCategory")).getNodeValue()%></option>
         <%
      }
   }
%>
</select>
</td>
</tr>
<tr>
<!--Display label for discussion field using resource bundle-->
<td width="194" bgcolor="#FFFFFF"><div align="center"><%= ds.getDiscussion()
%></div></td>
<td width="338" bgcolor="#FFFFFF">
<textarea name="txtDiscussion" rows="4" cols="50"></textarea>
</td>
</tr>
</table>
<p>
<!--Display label for submit button using resource bundle-->
<input type="submit" value=<%= ds.getSubmitQuery() %>>
</p>
</div>
</form>
End example

Download this listing.

The above code creates the AddDiscussion JSP file. The code retrieves the value of the String object, lang1, which is stored in session to create an object of the DisplayString class. The object of the DisplayString class retrieves country-specific data to provide the user interface of the AddDiscussion JSP page. When an end user specifies a topic, sub topic, and content of a discussion, and clicks the Submit button, the code parses the discussionlist.xml file to create an object tree of that file. The code adds a node that corresponds to the discussion in the object tree and transforms the object tree into an XML document. Figure 7-8 shows the user interface of AddDiscussion.jsp in French:

Click To expand: This figure shows the user interface of AddDiscussion.jsp in French. It contains fields in which an end user can specify information to start a new discussion.
Figure 7-8: User Interface of AddDiscussion.jsp in French

Creating the ViewDiscussion.jsp File

The ViewDiscussion.jsp file displays existing discussions and allows an end user to search for a specific discussion.

Listing 7-12 shows the content of the ViewDiscussion.jsp file:

Listing 7-12: The ViewDiscussion.jsp File
Start example
<!--Import the necessary packages-->
<%@page import="javax.xml.parsers.*, java.net.*, java.io.*, java.util.*, org.w3c.dom.*"%>
<%@page
import="javax.xml.transform.Transformer,javax.xml.transform.TransformerFactory, javax.xml.
transform.TransformerException"%>
<%@page
import="javax.xml.transform.TransformerConfigurationException, javax.xml.transform.dom.
DOMSource, javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%@page import="TxtConverter.*"%>
<%!String discussionpath;%>
<%
/*Call the constructor of DisplayString by passing the value of query parameter, lang*/
DisplayString ds=new DisplayString((session.getAttribute("lang1")).toString());
%>
<%
String tempCategory,tempSubCategory;
/*Retrieve values of category and sub category of discussion from request object*/
tempCategory = request.getParameter("txtCategory");
tempSubCategory = request.getParameter("txtSubCategory");
%>
<Center><H1 class="style1"><font color="#E24907"><%=
ds.getHeading()%></font></H1></Center>
<br>
<p align="center"><font size="5"><b>
<%= ds.getQueryList() %> </b></font>
</p>
<table border="0" width="215" cellspacing="0" cellpadding="0" height="1">
<tr>
<td width="95" bgcolor="#FFFFFF" height="1"><div align="center"><font
color="#FF0000"><b><%= ds.getUser() %>
</b></font></div></td>
<td width="104" bgcolor="#FFFFFF" height="1">
<font color="#FF0000"><b>
<%=session.getAttribute("userid")%> </b></font></td>
</tr>
</table>
<div align="justify">
<table border="0" cellpadding="0" cellspacing="0" width="200" style="position: absolute;
left: 713px; top: 115px; width: 207px" >
<tr>
<!---->
<td height="18" bgcolor="#FFFFFF"><font color="#FFFFFF"><b><a
href="DoLogout.jsp"><%= ds.getLogout() %></a></b></font></td>
</tr>
<tr>
<td height="18" bgcolor="#FFFFFF"><b>
<a href="UserPage.jsp">
<%= ds.getGoMain() %></a></b></td>
</tr>
</table>
</div>
<form action = ViewDiscussion.jsp method ="get">
<Center>
<table width="346" border="1" cellpadding="0" cellspacing="0" bordercolor="#FF0000">
<tr>
<td width="179" bgcolor="#FFFFFF"><%= ds.getCategory() %> </td>
<td width="153" bgcolor="#FFFFFF">
<select name="txtCategory" >
<option value=""></option>
<%
HashMap hmap = new HashMap();
try{
      /*Create a URL object to load properties file*/
      URL url=new URL("http://127.0.0.1:8080/seven/path.properties");
      /*Open URL connection*/
      URLConnection ucon=url.openConnection();
      /*Retrieve the discussionlistpath property*/
      Properties prop = new Properties();
      prop.load(ucon.getInputStream());
      discussionpath = prop.getProperty("discussionlistpath");
   }
   catch(Exception ex)
   {
      ex.printStackTrace();
   }
   /*Obtain a DocumentBuilder object by calling the newInstance()method*/
   DocumentBuilderFactory docbfact = DocumentBuilderFactory.newInstance();
   /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
   DocumentBuilder docb = docbfact.newDocumentBuilder();
   /*Parse the discussionlist XML document*/
   Document doc = docb.parse(new FileInputStream(discussionpath));
   /*Obtain query elemens of the XML document as a NodeList object*/
   NodeList nl1 = doc.getElementsByTagName("query");
   /*Iterate through the NodeList object*/
   for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
   {
       /*Obtain the Node object*/
      Node n=nl1.item(int_1);
       /*Retrieve attributes of the Node objects*/
      NamedNodeMap nnp = n.getAttributes();
      Object obj1 =
 hmap.put((nnp.getNamedItem("Category")).getNodeValue(),(nnp.getNamedItem("Category")).
 getNodeValue());
      if(obj1==null)
      {
         %>
         <!--Populate category drop-down list with values of Category attributes-->
         <option><%=(nnp.getNamedItem("Category")).getNodeValue()%></option>
         <%
      }
   }
%>
</select></td>
</tr>
<tr>
<td width="179" height="26" bgcolor="#FFFFFF"><%= ds.getSubCategory() %> </td>
<td width="153" bgcolor="#FFFFFF">
<!--Display sub-category drop-down list-->
<select name="txtSubCategory" >
<option value=""></option>
<%
hmap = new HashMap();
/*Obtain a DocumentBuilder object by calling the newInstance()method*/
docbfact = DocumentBuilderFactory.newInstance();
/*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
docb = docbfact.newDocumentBuilder();
/*Parse the discussionlist XML document*/
doc = docb.parse(new FileInputStream(discussionpath));
/*Obtain query elemens of the XML document as a NodeList object*/
nl1 = doc.getElementsByTagName("query");
/*Iterate through the NodeList object*/
for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
   {
      /*Obtain the Node object that represents elements of an XML document*/
      Node n=nl1.item(int_1);
     /*Retrieve attributes of the Node objects*/
      NamedNodeMap nnp = n.getAttributes();
      Object obj1 = hmap.put((nnp.getNamedItem("SubCategory")).getNodeValue(),
      (nnp.getNamedItem("SubCategory")).
      getNodeValue());
      if(obj1==null)
      {
         %>
         <!--Populate category drop-down list with values of SubCategory attributes-->
         <option
    value="<%=(nnp.getNamedItem("SubCategory")).getNodeValue()%>"><%=
    (nnp.getNamedItem("SubCategory")).getNodeValue()%></option>
         <%
      }
   }
   %>
   </select></td>
   </tr>
   </table>
   <p>
   <input type="submit" value= <%= ds.getViewDiscussion() %>">
   </p>
   </Center>
   </form>
   <div align="justify">
   <table width="300" border="1" cellpadding="0" cellspacing="0" bordercolor="#FF0000"
   style="position: absolute; left: 335px; top: 311px; width: 371px;">
   <tr bgcolor="#FFFFFF">
   <td colspan="3">
   <!--Call getExistingDiscussion() method of DisplayString object to display country
   specific data-->
   <p align="center"><i><font color="#FF0000"><b> <%=
   ds.getExistingDiscussion() %> </b></font></i></p>
   </td>
   </tr>
   <tr>
   <td width="147" bgcolor="#FFFFFF"><font color="#FF0000"><b>&nbsp;<%=
   ds.getCategory() %></b></font></td>
   <td width="147" bgcolor="#FFFFFF"><font color="#FF0000"><b><%=
   ds.getSubCategory() %></b></font></td>
   <td width="147" bgcolor="#FFFFFF"><font color="#FF0000"><b><%=
   ds.getDiscussion() %></b></font></td>
   </tr>
   <%
   hmap = new HashMap();
   /*Obtain a DocumentBuilder object by calling the newInstance()method*/
   docbfact = DocumentBuilderFactory.newInstance();
   /*Call the newDocumentBuilder() method to obtain a DocumentBuilder object*/
   docb = docbfact.newDocumentBuilder();
   /*Parse the discussionlist XML document*/
   doc = docb.parse(new FileInputStream(discussionpath));
   /*Obtain query elemens of the XML document as a NodeList object*/
   nl1 = doc.getElementsByTagName("query");
   /*Iterate through the NodeList object*/
   for(int int_1 = 0; int_1 < nl1.getLength(); int_1 ++)
   {/*If end user does not specifies any search criteria display all discussion data*/
   Node n=nl1.item(int_1);
   NamedNodeMap nnp = n.getAttributes();
   if(tempCategory == null && tempSubCategory == null )
   {
      %>
      <tr>
      <td width="147"
      bgcolor="#FFFFFF"><%=(nnp.getNamedItem("Category")).getNodeValue()%></td>
      <td width="147"
  bgcolor="#FFFFFF"><%=(nnp.getNamedItem("SubCategory")).getNodeValue()%></td>
      <td width="147"
 bgcolor="#FFFFFF"><%=(nnp.getNamedItem("Discussion")).getNodeValue()%></td>
      </tr>
      <%
   }
   else
   {
      if (!(tempCategory.equals("")))
      {
         if ((nnp.getNamedItem("Category")).getNodeValue().equals(tempCategory))
         {
            /*If end user specifies a category,match end user category with the node value. For
            /* matching categories, display discussion data.*/
            %>
            <tr>
            <td width="147"
 bgcolor="#FFFFFF"><%=(nnp.getNamedItem("Category")).getNodeValue()%></td>
            <td width="147"
 bgcolor="#FFFFFF"><%=(nnp.getNamedItem("SubCategory")).getNodeValue()%></td>
            <td width="147"
 bgcolor="#FFFFFF"><%=(nnp.getNamedItem("Discussion")).getNodeValue()%></td>
            </tr>
            <%
         }
      }
      else
      {
         if (!(tempSubCategory.equals("")))
         {
            if ((nnp.getNamedItem("SubCategory")).getNodeValue().equals(tempSubCategory))
            {
               /*If end user specifies both category and sub category,match end user sub
               category with the node value. For matching categories, display discussion data.*/
               %>
               <tr>
               <td width="147"
 bgcolor="#FFFFFF"><%=(nnp.getNamedItem("Category")).getNodeValue()%></td>
               <td width="147"
 bgcolor="#FFFFFF"><%=(nnp.getNamedItem("SubCategory")).getNodeValue()%></td>
               <td width="147"
 bgcolor="#FFFFFF"><%=(nnp.getNamedItem("Discussion")).getNodeValue()%></td>
               </tr>
               <%
            }
         }
      }
   }
}
%>
</table>
</div>
End example

Download this listing.

The above code creates the ViewDiscussion JSP page. The code creates an object of the DisplayString class to display country-specific data. The parse() method of the DocumentBuilder object parses the discussionlist.xml file and retrieves values of the Category and SubCategory attributes. The Topic and Sub Topic drop-down lists display the attribute values. When an end user selects a topic or sub topic to view discussions, the code iterates through the object tree node of the discussionlist XML document to retrieve data of all matching discussions. The code displays the data in the country-specific user interface in a tabular format.

Figure 7-9 shows the user interface provided by the ViewDiscussion JSP page in French:

Click To expand: This figure shows the user interface of the ViewDiscussion JSP page. It contains drop-down lists that allow an end user to select a topic or sub topic to view discussions.
Figure 7-9: User Interface of the ViewDiscussion JSP Page in French


Creating the Property File

The online discussion forum application uses a property file to store the path to the XML files of the application. The following code shows the path.properties property file of the application:

userlistpath=c:/Chp7/code/xml/userlist.xml
discussionlistpath=c:/Chp7/code /xml/discussionlist.xml
uslistpath=c:/Chp7/code/xml/uslist.xml
francelistpath=c:/Chp7/code/xml/francelist.xml

The above code contains the following properties:

  • userlistpath: Stores the path to the userlist.xml file.

  • discussionistpath: Stores the path to the discussionlist.xml file.

  • uslistpath: Stores the path to the uslist.xml file.

  • francelistpath: Stores the path to the francelist.xml file.

Note

The property values in the path.properties file specify the path to the XML files of the application. If you store the XML files in some other location, you need to change the property values to specify the new path of the XML files.


Unit Testing

You need to deploy and test the online discussion forum application on the Sun Java System Application Server Platform Edition 8. You can download this application server from:

http://java.sun.com/j2ee/1.4/download.html

Note

To install the Sun Java System Application Server Platform Edition 8, you need to install Java 2 Standard Edition (J2SE) 1.4.2 on the computer.

To deploy the discussion forum application:

  1. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Start Default Server from the Start menu to start the application server.

  2. Select Programs->Sun Microsystems->J2EE 1.4 SDK ->Deploytool from the Start menu to open the Deployment Tool window.

  3. Select New->Application from the File menu of the Deployment Tool window to create a new application. The New Application dialog box appears.

  4. Click Browse in the New Application dialog box. Another New Application dialog box appears.

  5. In the New Application dialog box, use the Look In combo box to select the directory in which you want to save the .ear file of the application.

  6. Specify OnlineDiscussionForumApp as the name of the application file in the File Name text box, as shown in Figure 7-10:

    Click To expand: This figure shows the New Application dialog box in which you can specify the name of the application file and its location.
    Figure 7-10: The New Application Dialog Box

  7. Click the New Application button to return to the previous New Application dialog box.

  8. Click OK to create the new application.

  9. Select New->Web Component from the File menu of the Deployment Tool window. The New Web Application Wizard-Introduction dialog box appears.

  10. Click Next. The New Web Application Wizard-Web Archive (WAR) File dialog box appears.

  11. Click Edit Contents in the New Web Application Wizard-WAR File dialog box. The Edit Contents of WebApp dialog box appears.

  12. Select the JSP files, image files, and the path.properties file of the application from the Available Files pane and click Add. Select the DisplayString.class and LangusageDocParser.class files and click Add. The Contents of WebApp pane displays the added files, as shown in Figure 7-11:

    Click To expand: This figure shows the Edit Contents of WebApp dialog box that displays the files of the online discussion forum application.
    Figure 7-11: The Edit Contents of WebApp Dialog Box

  13. Click OK to add the files to the Web application WAR file.

  14. Click Next in the New Web Application Wizard-WAR File dialog box. The New Web Application Wizard-Choose Component Type dialog box appears.

  15. Select the JSP Page radio button and click Next. The New Web Application Wizard-Component General Properties dialog box appears.

  16. Select Index.jsp from the JSP Filename drop-down list. The remaining fields get automatically populated with values. Figure 7-12 shows the New Web Application Wizard-Component General Properties dialog box:

    Click To expand: This figure shows the New Web Application Wizard-Component General Properties dialog box in which you specify the main page of your application.
    Figure 7-12: The New Web Application Wizard-Component General Properties Dialog Box

  17. Click Finish.

  18. In the Deployment Tool window, specify/seven as the context root of your application in the Context Root text field, as shown in Figure 7-13:

    Click To expand: This figure shows the Context Root text field of the Deployment Tool window, in which you can specify the context root of the application.
    Figure 7-13: The Deployment Tool Window

  19. Select Save from the File menu of the Deployment Tool window to save the application.

  20. Select Deploy from the Tools menu. The Deploy Module OnlineDiscussionForumApp dialog box appears.

  21. Specify the application server user name and password in the relevant fields and click OK.

  22. The Distribute Module dialog box appears, which indicates the successful deployment of the application.

To test the deployed application:

  1. Type the following URL in the address bar of the browser:

    http://localhost:8080/seven/Index.jsp

    The Index JSP page appears, as shown in Figure 7-14:

    Click To expand: This figure shows the Index JSP page that displays the United States and France hyperlinks.
    Figure 7-14: The Index JSP Page

  2. Select the United States hyperlink. The Logon JSP page appears, which displays the user interface in US English. Specify Peter in the User ID field and peter in the Password field, as shown in Figure 7-15:

    Click To expand: This figure shows the Logon JSP page that provides the User ID and Password fields to accept logon information.
    Figure 7-15: The Logon JSP Page

  3. Click the Submit button. The DoLogon page appears, as shown in Figure 7-16:

    Click To expand: This figure shows the DoLogon page that displays a welcome message and the Logout and Go to main page hyperlinks.
    Figure 7-16: The DoLogon Page

  4. Select the Go to main page hyperlink. The User Options page appears, as shown in Figure 7-17:

    Click To expand: This figure shows the User Options page that displays the Start a new discussion and View discussion hyperlinks.
    Figure 7-17: The User Options Page

  5. Select the Start a new discussion hyperlink. The Post Message page appears. Specify a discussion topic, sub topic, and content for the discussion, as shown in Figure 7-18:

    Click To expand: This figure shows the Post Message page that displays the Topic, Sub Topic, and Discussion fields in which you can specify the content to start a discussion.
    Figure 7-18: The Post Message Page

  6. Click the Submit button to record the content in the discussionlist.xml file.

  7. In the User Options page, select the View discussion hyperlink. The View Discussion page appears.

  8. Select a topic or sub topic from the Topic or Sub Topic drop-down list and click View. The View Discussion page displays the discussions listed under the selected topic or sub topic, as shown in Figure 7-19:

    Click To expand: This figure shows the View Discussion page in which you can select a topic or sub topic to view the discussions.
    Figure 7-19: The View Discussion Page

  9. Select the Logout hyperlink to return to the home page. Click the France hyperlink to participate in the discussion forum in French.


Index

A-J

Application Programming Interfaces, Chapter 1: Creating Web Applications Using XML-Based JSP Documents
Document Object Model, Chapter 1: Creating Web Applications Using XML-Based JSP Documents, Chapter 2: Creating a JSP Application to Process and Transform XML Documents Using JAXP, Chapter 3: Creating a JSPXML Integrated System Using JDOM
Document Type Definition, Chapter 1: Creating Web Applications Using XML-Based JSP Documents
Extensible Markup Language, Chapter 1: Creating Web Applications Using XML-Based JSP Documents
Extensible Stylesheet Language, Chapter 4: Generating Dynamic XML Content in JSP Applications
HTML, Chapter 4: Generating Dynamic XML Content in JSP Applications
internationalized application, Chapter 7: Creating an Internationalized Application Using JSP and XML
Java Document Object Model, Chapter 3: Creating a JSPXML Integrated System Using JDOM
Java Standard Tag Library, Chapter 1: Creating Web Applications Using XML-Based JSP Documents
Java 2 Enterprise Edition, Chapter 1: Creating Web Applications Using XML-Based JSP Documents
JavaServer Pages, Chapter 1: Creating Web Applications Using XML-Based JSP Documents
JavaServer Pages Standard Tag Library, Chapter 6: Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications
JSP, Chapter 2: Creating a JSP Application to Process and Transform XML Documents Using JAXP, Chapter 4: Generating Dynamic XML Content in JSP Applications, Chapter 5: Developing JSP Custom Tags for Integrating and Displaying XML Data, Chapter 6: Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications, Chapter 7: Creating an Internationalized Application Using JSP and XML


Index_S-X

Team LiB

Index

S-X

Simple API for XML, Chapter 3: Creating a JSPXML Integrated System Using JDOM
Tag Library Descriptor, Chapter 5: Developing JSP Custom Tags for Integrating and Displaying XML Data
Tag Library Descriptors, Chapter 6: Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications
XML, Chapter 4: Generating Dynamic XML Content in JSP Applications, Chapter 5: Developing JSP Custom Tags for Integrating and Displaying XML Data, Chapter 6: Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications, Chapter 7: Creating an Internationalized Application Using JSP and XML, Requirements of the Online Discussion Forum Application


List of Figures

Point 1: Creating Web Applications Using XML-Based JSP Documents

Figure 1-1: Architecture of the Online Retail Application
Figure 1-2: The Logon Page
Figure 1-3: The User Options Page
Figure 1-4: The View All Items Page
Figure 1-5: The Purchase Items Page
Figure 1-6: The View Total Purchase Page
Figure 1-7: The Administrator Options Page
Figure 1-8: The Manage Items Page
Figure 1-9: The View Sales Page
Figure 1-10: The Connection Pools Page
Figure 1-11: The Wizard Step 1 Section
Figure 1-12: The Create JDBC Resource Page
Figure 1-13: The New Application Dialog Box
Figure 1-14: The Edit Contents of WebApp Dialog Box
Figure 1-15: The New Web Application Wizard-Choose Component Type Dialog Box
Figure 1-16: The New Web Application Wizard-Component General Properties Dialog Box
Figure 1-17: The Deployment Tool Window
Figure 1-18: The Distribute Module Dialog Box
Figure 1-19: Specifying the User ID and Password
Figure 1-20: The Administrator Options Page
Figure 1-21: Specifying Information for a New Item
Figure 1-22: Items Available in the Store
Figure 1-23: Updating Item Records
Figure 1-24: Logging on to the User Module
Figure 1-25: Specifying Purchase Quantity
Figure 1-26: Records of Purchases

Point 2: Creating a JSP Application to Process and Transform XML Documents Using JAXP

Figure 2-1: Architecture of the Online Music Store Application
Figure 2-2: Logon Page
Figure 2-3: User Interface of the DoLogon Page for Administrator Role
Figure 2-4: User Interface of the DoLogon Page for User Role
Figure 2-5: Administrator Options Page
Figure 2-6: Add New User Page
Figure 2-7: Delete User Page
Figure 2-8: Add Music Album Page
Figure 2-9: Delete Music Album Page
Figure 2-10: Add Video Album Page
Figure 2-11: Delete Video Album Page
Figure 2-12: Purchase Album Page
Figure 2-13: New Application Dialog Box
Figure 2-14: Edit Contents of WebApp Dialog Box
Figure 2-15: New Web Application Wizardt General Properties Dialog Box
Figure 2-16: Deployment Tool Window
Figure 2-17: Specifying Logon Information
Figure 2-18: Administrator Options Page Containing Hyperlinks
Figure 2-19: Add User Page
Figure 2-20: List of Existing Users Table
Figure 2-21: Selecting a User Name
Figure 2-22: Specifying Album Information
Figure 2-23: Existing Albums Table
Figure 2-24: Deleting a Music Album
Figure 2-25: User Interface of the DoLogon JSP Page
Figure 2-26: Specifying the Album Name
Figure 2-27: DoLogon Page Displaying Purchased Album

Point 3: Creating a JSPXML Integrated System Using JDOM

Figure 3-1: Architecture of the Online Directory Application
Figure 3-2: The User Logon Page
Figure 3-3: User Interface of the DoLogon JSP Page for Administrator Role
Figure 3-4: User Interface of the DoLogon JSP Page for User Role
Figure 3-5: The User Registration Page
Figure 3-6: The Administrator Options Page
Figure 3-7: The Add Entry Page
Figure 3-8: The Delete Entry Page
Figure 3-9: The User Options Page
Figure 3-10: The Search by Category Page
Figure 3-11: The Search by City Page
Figure 3-12: The Search by Zip Code Page
Figure 3-13: The New Application Dialog Box
Figure 3-14: The Edit Contents of WebApp Dialog Box
Figure 3-15: The New Web Application Wizard-Component General Properties Dialog Box
Figure 3-16: The Deployment Tool Window
Figure 3-17: Specifying User ID and Password
Figure 3-18: The DoLogon JSP page for Administrator Role
Figure 3-19: Selecting the Go to admin page Hyperlink
Figure 3-20: Specifying Information
Figure 3-21: User Interface of the DoAddEntry JSP Page
Figure 3-22: Deleting an Entry
Figure 3-23: User Interface of the DeleteEntry JSP Page
Figure 3-24: The User Registration Page
Figure 3-25: User Interface of the DoLogon JSP Page
Figure 3-26: Selecting a Hyperlink
Figure 3-27: Specifying a Category
Figure 3-28: Organizations for a Specified Category

Point 4: Generating Dynamic XML Content in JSP Applications

Figure 4-1: Architecture of the Online Technical Support Application
Figure 4-2: User Interface of the Logon JSP Page
Figure 4-3: The User Options Page
Figure 4-4: The New Query Page
Figure 4-5: The Administrator Options Page
Figure 4-6: The Query Reply Page
Figure 4-7: The View Query Page
Figure 4-8: The New Application Dialog Box
Figure 4-9: The Edit Contents of WebApp Dialog Box
Figure 4-10: The New Web Application Wizard-Component General Properties Dialog Box
Figure 4-11: The Deployment Tool Window
Figure 4-12: The Logon JSP Page
Figure 4-13: The User Options Page Containing Hyperlinks
Figure 4-14: Posting a Query
Figure 4-15: The Administrator Options Page Containing Hyperlinks
Figure 4-16: Posting a Reply
Figure 4-17: Selecting a Query Format
Figure 4-18: Dynamically Generated XML Content
Figure 4-19: Query in HTML Format
Figure 4-20: The File Download Dialog Box
Figure 4-21: The Save As Dialog Box

Point 5: Developing JSP Custom Tags for Integrating and Displaying XML Data

Figure 5-1: Architecture of the Online Article Processing Application
Figure 5-2: The Logon Page
Figure 5-3: The Administer Article Page
Figure 5-4: The User Page
Figure 5-5: The View Articles Page for Administrator Role
Figure 5-6: The View Articles Page for User Role
Figure 5-7: The Article Ratings Page
Figure 5-8: The New Application Dialog Box
Figure 5-9: The Edit Contents of WebApp Dialog Box
Figure 5-10: The New Web Application Wizard-Component General Properties Dialog Box
Figure 5-11: The Deployment Tool Window
Figure 5-12: Specifying Logon Information
Figure 5-13: The User Interface of the DoLogin JSP Page for Administrator Role
Figure 5-14: The Add Article Table of the Administer Article Page
Figure 5-15: User Interface of the DoAddArticle JSP Page
Figure 5-16: The View Article Page
Figure 5-17: The User Interface of the DoLogin JSP Page for User Role
Figure 5-18: Searching an Article
Figure 5-19: Rating an Article
Figure 5-20: User Interface of the DoRateArticle JSP Page
Figure 5-21: Displaying Article Ratings

Point 6: Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications

Figure 6-1: Architecture of the Online News Application
Figure 6-2: The MainPage JSP Page
Figure 6-3: The MainNewsPage JSP Page
Figure 6-4: The NewsDetailPage JSP Page
Figure 6-5: The SearchNewsPage JSP Page
Figure 6-6: The DoSearchNews JSP Page
Figure 6-7: The New Application Dialog Box
Figure 6-8: The Edit Contents of WebApp Dialog Box
Figure 6-9: The New Web Application Wizard- Component General Properties Dialog Box
Figure 6-10: The Deployment Tool Window
Figure 6-11: The MainPage JSP Page
Figure 6-12: The MainNews JSP Page
Figure 6-13: The NewsDetailPage JSP Page
Figure 6-14: The SearchNewsPage JSP Page
Figure 6-15: The DoSearchNews JSP Page

Point 7: Creating an Internationalized Application Using JSP and XML

Figure 7-1: Architecture of the Online Discussion Forum Application
Figure 7-2: The Home Page
Figure 7-3: User Interface of Logon.jsp File for US
Figure 7-4: User Interface of Logon.jsp File for France
Figure 7-5: User Interface of DoLogon JSP for US on Successful Authentication
Figure 7-6: User Interface of DoLogon JSP for France on Unsuccessful Authentication
Figure 7-7: User Interface of UserPage JSP in French
Figure 7-8: User Interface of AddDiscussion.jsp in French
Figure 7-9: User Interface of the ViewDiscussion JSP Page in French
Figure 7-10: The New Application Dialog Box
Figure 7-11: The Edit Contents of WebApp Dialog Box
Figure 7-12: The New Web Application Wizard-Component General Properties Dialog Box
Figure 7-13: The Deployment Tool Window
Figure 7-14: The Index JSP Page
Figure 7-15: The Logon JSP Page
Figure 7-16: The DoLogon Page
Figure 7-17: The User Options Page
Figure 7-18: The Post Message Page
Figure 7-19: The View Discussion Page


List of Examples

Point 1: Creating Web Applications Using XML-Based JSP Documents

Listing 1-1: The database.sql File
Listing 1-2: The Logon.jspx File
Listing 1-3: The DoLogon.jspx File
Listing 1-4: The LogonHandler.java File
Listing 1-5: The User.java Class
Listing 1-6: The UserPage.jspx File
Listing 1-7: The ViewAllItems.jspx File
Listing 1-8: The PurchaseItems.jspx File
Listing 1-9: The DoPurchase.jspx File
Listing 1-10: The ViewTotalPurchase.jspx File
Listing 1-11: The AdminPage.jspx File
Listing 1-12: The ManageItem.jspx File
Listing 1-13: The GetAllItems.jspx File
Listing 1-14: The AddItem.jspx File
Listing 1-15: The UpdateItem.jspx File
Listing 1-16: The ViewSales.jspx File

Point 2: Creating a JSP Application to Process and Transform XML Documents Using JAXP

Listing 2-1: The userlist.xml File
Listing 2-2: The musicalbumlist.xml File
Listing 2-3: The videoalbumlist.xml File
Listing 2-4: The musicpurchaselist.xml File
Listing 2-5: The videopurchaselist.xml File
Listing 2-6: The Logon.jsp File
Listing 2-7: The DoLogon.jsp File
Listing 2-8: The AdministratorPage.jsp File
Listing 2-9: The AddUser.jsp File
Listing 2-10: The DeleteUser.jsp File
Listing 2-11: The AddMusicAlbum.jsp File
Listing 2-12: The DeleteMusicAlbum.jsp File
Listing 2-13: The AddVideoAlbum.jsp File
Listing 2-14: The DeleteVideoAlbum.jsp File
Listing 2-15: The PurchaseAlbum.jsp File

Point 3: Creating a JSPXML Integrated System Using JDOM

Listing 3-1: The userlist.xml File
Listing 3-2: The directorylist.xml File
Listing 3-3: The Logon.jsp File
Listing 3-4: The DoLogon.jsp File
Listing 3-5: The UserRegistration.jsp File
Listing 3-6: The RegisterUser.jsp File
Listing 3-7: The AdminPage.jsp File
Listing 3-8: The AddEntry.jsp File
Listing 3-9: The DoAddEntry.jsp File
Listing 3-10: The DeleteEntry.jsp File
Listing 3-11: The DoDeleteEntry.jsp File
Listing 3-12: The UserPage.jsp File
Listing 3-13: The Category.jsp File
Listing 3-14: The City.jsp File
Listing 3-15: The Zip.jsp File

Point 4: Generating Dynamic XML Content in JSP Applications

Listing 4-1: The userlist.xml File
Listing 4-2: The querylist.xml File
Listing 4-3: The Logon.jsp File
Listing 4-4: The DoLogon.jsp File
Listing 4-5: The DoLogout.jsp File
Listing 4-6: The UserPage.jsp File
Listing 4-7: The NewQuery.jsp File
Listing 4-8: The AdminPage.jsp File
Listing 4-9: The QueryReply.jsp File
Listing 4-10: The ViewQueryList.jsp File
Listing 4-11: The ViewQuery.jsp File
Listing 4-12: The QueryXMLGenerator Class
Listing 4-13: The technicalhelpdesk.xsl File

Point 5: Developing JSP Custom Tags for Integrating and Displaying XML Data

Listing 5-1: The userlist.xml File
Listing 5-2: The articlelist.xml File
Listing 5-3: The technicaldocs-taglib.tld File
Listing 5-4: The LoginPage.jsp File
Listing 5-5: The DoLogin.jsp File
Listing 5-6: The ShowHeaderTag.java File
Listing 5-7: The ShowFooterTag.java File
Listing 5-8: The ShowloginTag.java File
Listing 5-9: The DoLoginTag.java File
Listing 5-10: The AdminPage.jsp File
Listing 5-11: The UserPage.jsp File
Listing 5-12: The FrmSearchTag.java File
Listing 5-13: The DoSearchArticle.jsp File
Listing 5-14: The ShowArticleTag.java File
Listing 5-15: The FormAddArticleTag.java File
Listing 5-16: The DoAddArticle.jsp File
Listing 5-17: The DoAddArticleTag.java File
Listing 5-18: The ModifyDeleteRate.jsp File
Listing 5-19: The DoUpdateArticle.jsp File
Listing 5-20: The DoUpdateArticleTag.java File
Listing 5-21: The DoDeleteArticle.jsp File
Listing 5-22: The DoDeleteArticleTag.java File
Listing 5-23: The DoRateArticle.jsp File
Listing 5-24: The DoRateArticleTag.java File
Listing 5-25: The ArticleRatings.jsp File
Listing 5-26: The ShowArticleRating.java File

Point 6: Using JavaServer Pages Standard Tag Library (JSTL) Tags in JSP XML Applications

Listing 6-1: The userlist.xml File
Listing 6-2: The newslist.xml File
Listing 6-3: The MainPage.jsp File
Listing 6-4: The DoLogon.jsp File
Listing 6-5: The DoLogout.jsp File
Listing 6-6: The MainNewsPage.jsp File
Listing 6-7: The NewsDetailsPage.jsp File
Listing 6-8: The SearchNewsPage.jsp File
Listing 6-9: The DoSearchNews.jsp File

Point 7: Creating an Internationalized Application Using JSP and XML

Listing 7-1: The userlist.xml File
Listing 7-2: The discussionlist.xml File
Listing 7-3: The uslist.xml File
Listing 7-4: The francelist.xml File
Listing 7-5: The LanguageDocParser.java File
Listing 7-6: The DisplayString.java File
Listing 7-7: The Index.jsp File
Listing 7-8: The Logon.jsp File
Listing 7-9: The DoLogon.jsp File
Listing 7-10: The UserPage.jsp File
Listing 7-11: The AddDiscussion.jsp File
Listing 7-12: The ViewDiscussion.jsp File


CD Content

Team LiB
Previous Section

CD Content CD Content

Following are select files from this book's Companion CD-ROM. These files are copyright protected by the publisher, author, and/or other third parties. Unauthorized use, reproduction, or distribution is strictly prohibited.

File | Description | Size
All CD Content | Java InstantCode: Developing JSP and XML Integrated Solutions | 126,103
Chapter 1 |  | 18,395
Chapter 2 |  | 24,930
Chapter 3 |  | 21,834
Chapter 4 |  | 14,980
Chapter 5 |  | 23,749
Chapter 6 |  | 8,697
Chapter 7 |  | 13,650

Team LiB
Previous Section


backcover

Team LiB

Java InstantCode: Developing JSP and XML Integrated Solutions - Books24x7.com - Referenceware for Professionals MyHome MyAccount Settings Help Feedback Login Text Only
fosteam@skil.com | NACCB
Search:
Browse Browse Tools:
Add to Bookshelf folders
Tips Tips
Contents
Related Links:
InstantCode Series

Collections:
 | BusinessPro
Full access in collection | ITPro
 | OfficeEssentials
Java InstantCode: Developing JSP and XML Integrated Solutions
Java InstantCode: Developing JSP and XML Integrated Solutions
SkillSoft © 2004

Use this code-intensive reference to learn about developing JSP and XML integrated solutions using XML-based JSP documents, the Java API for XML Processing (JAXP), and JDOM.

Has CD Content