Java Web Programming With Eclipse
Java Web Programming With Eclipse
Table of Contents
1 Preface...............................................................................................................................................................1 1.1 Overview............................................................................................................................................1 1.2 How to Read This Book .....................................................................................................................1 2 Introduction to Java Web Application Development...................................................................................2 2.1 Objectives..........................................................................................................................................2 2.2 Overview............................................................................................................................................2 2.3 Computer Languages Used for Web Application Development.......................................................2 2.4 The Servlet API ..................................................................................................................................3 2.5 Java 2 Enterprise Edition (J2EE).......................................................................................................3 2.6 Java Server Pages (JSP).....................................................................................................................3 2.7 Rich Site Summary (RSS).................................................................................................................4 2.8 Representational State Transfer (REST) ............................................................................................4 2.9 Web Services.....................................................................................................................................4 2.10 Integrated Development Environments...........................................................................................4 2.11 Ant...................................................................................................................................................5 2.12 Web Application Architecture.........................................................................................................5 2.13 Security............................................................................................................................................6 2.14 Web Application Servers.................................................................................................................6 2.15 Database Servers..............................................................................................................................6 2.16 Development versus Deployment Environments .............................................................................6 3 Java Web Programming with Eclipse............................................................................................................8 4 Java Setup.........................................................................................................................................................9 4.1 Objectives..........................................................................................................................................9 4.2 Overview............................................................................................................................................9 4.3 Installation.........................................................................................................................................9 4.4 Exercises............................................................................................................................................9 4.4.1 (1) Test Installation..................................................................................................................9 4.5 Notes..................................................................................................................................................9 5 Eclipse Setup ...................................................................................................................................................11 5.1 Objectives........................................................................................................................................11 5.2 Overview..........................................................................................................................................11 5.3 Installation.......................................................................................................................................11 5.4 Issues................................................................................................................................................11 5.4.1 64-Bit Windows.....................................................................................................................11 5.5 Configure File Types.......................................................................................................................12 5.6 Exercises..........................................................................................................................................12 5.6.1 (1) Workbench Basic Tutorial................................................................................................13 5.6.2 (2) Java Development Basic Tutorial.....................................................................................13 6 The Apache Tomcat Web Container ............................................................................................................14 6.1 Objectives........................................................................................................................................14 6.2 Overview..........................................................................................................................................14 6.3 Install Tomcat..................................................................................................................................14 6.4 Test ...................................................................................................................................................14 i
Table of Contents
6 The Apache Tomcat Web Container 6.5 Issues................................................................................................................................................15 6.5.1 Tomcat doesn't start under Vista............................................................................................15 6.5.2 Tomcat doesn't start under Windows.....................................................................................15 6.6 Configure Firewall...........................................................................................................................16 6.7 Manager Application.......................................................................................................................16 6.8 Tomcat Documentation ....................................................................................................................17 6.9 Log Files..........................................................................................................................................18 6.9.1 Overview................................................................................................................................18 6.9.2 Logwatcher Installation..........................................................................................................19 6.9.3 LogWatcher Usage.................................................................................................................19 6.10 Understanding Tomcat Class Loading...........................................................................................19 6.11 Deep Restart of Tomcat.................................................................................................................19 6.11.1 Overview..............................................................................................................................20 6.11.2 Deep Restart Procedure........................................................................................................20 6.12 Exercises........................................................................................................................................20 6.12.1 (1) Servlet API ......................................................................................................................20 6.12.2 (2) Firewall Experiments......................................................................................................20 6.12.3 (3) Log Files.........................................................................................................................20 6.12.4 (4) Deep Restart ....................................................................................................................20 7 Java Servlets...................................................................................................................................................22 7.1 Objectives........................................................................................................................................22 7.2 References........................................................................................................................................22 7.3 Overview..........................................................................................................................................22 7.4 Project Creation...............................................................................................................................22 7.5 Attaching Source Code to Jar Files ..................................................................................................24 7.6 Deployment Descriptor....................................................................................................................25 7.6.1 Deployment Descriptor web.xml...........................................................................................26 7.7 Create Home Servlet........................................................................................................................27 7.7.1 HomeServlet.java...................................................................................................................32 7.8 Web Application Deployment.........................................................................................................33 7.9 Exercises..........................................................................................................................................34 7.9.1 (1) Servlet Mapping Element.................................................................................................34 7.9.2 (2) Methods doGet and doPost...............................................................................................34 7.9.3 (3) Adding Two Numbers......................................................................................................34 8 Web Application Logging ..............................................................................................................................35 8.1 Objectives........................................................................................................................................35 8.2 References........................................................................................................................................35 8.2.1 Overview................................................................................................................................35 8.2.2 Add the Log4j Library to the Project.....................................................................................35 8.2.3 Create the Log4j Configuration File......................................................................................37 8.2.4 Observe the Eclipse Build Process.........................................................................................38 8.2.5 Modify HomeServlet..............................................................................................................38 8.3 Exercises..........................................................................................................................................41 8.3.1 (1) Attach Source Code..........................................................................................................41
ii
Table of Contents
9 Java Server Pages..........................................................................................................................................43 9.1 Objectives........................................................................................................................................43 9.2 References........................................................................................................................................43 9.3 Overview..........................................................................................................................................43 9.4 Create a JSP.....................................................................................................................................45 9.4.1 home.jsp.................................................................................................................................45 9.4.2 Modify HomeServlet..............................................................................................................46 9.4.3 Test.........................................................................................................................................48 9.5 Exercises..........................................................................................................................................50 9.5.1 (1) Methods doGet and doPost, Revisited..............................................................................50 9.5.2 (2) Adding Two Numbers, Revisited.....................................................................................50 10 A Simple News Feed Application ................................................................................................................52 10.1 Objectives......................................................................................................................................52 10.2 References......................................................................................................................................52 10.3 Overview........................................................................................................................................52 10.3.1 Flow of information for RSS................................................................................................53 10.4 Install Libraries..............................................................................................................................53 10.4.1 Modify HomeServlet............................................................................................................53 10.4.2 Modified HomeServlet.java for RSS News.........................................................................54 10.5 Modify the JSP ...............................................................................................................................55 10.5.1 Modified home.jsp for RSS News ........................................................................................55 10.6 Test .................................................................................................................................................56 10.7 Create Publisher Project .................................................................................................................56 10.7.1 Initial web.xml file for the publisher project ........................................................................56 10.8 Exercises........................................................................................................................................57 10.8.1 (1) Include someone else's news..........................................................................................57 10.8.2 (2) Display More Information..............................................................................................57 11 The MySQL Database Server.....................................................................................................................59 11.1 Objectives......................................................................................................................................59 11.2 References......................................................................................................................................59 11.2.1 From the MySQL Manual (version 5.1) ...............................................................................59 11.3 Overview........................................................................................................................................59 11.4 Install MySQL...............................................................................................................................59 11.4.1 Secure Server Against Outside Access................................................................................60 11.4.2 Configure Firewall...............................................................................................................60 11.4.3 Test.......................................................................................................................................60 11.5 MySQL-Specific Commands.........................................................................................................62 11.5.1 List Databases .......................................................................................................................62 11.5.2 Quit.......................................................................................................................................62 11.5.3 Cancel Partially Entered Command.....................................................................................62 11.5.4 Select a Database..................................................................................................................62 11.5.5 Create a Database.................................................................................................................62 11.5.6 Drop a Database...................................................................................................................62 11.5.7 Describe a Table...................................................................................................................63 11.6 Basic SQL Commands...................................................................................................................63 11.6.1 Create a Table .......................................................................................................................63 iii
Table of Contents
11 The MySQL Database Server 11.6.2 Drop a Table.........................................................................................................................63 11.6.3 Insert Data............................................................................................................................63 11.6.4 Retrieve Data From a Single Table......................................................................................63 11.6.5 Examples..............................................................................................................................63 11.7 Create a Database of News Items..................................................................................................65 11.8 Create Ant Build File.....................................................................................................................67 11.9 Run Targets....................................................................................................................................67 11.10 Exercises......................................................................................................................................69 11.10.1 (1) MAX function ...............................................................................................................69 11.10.2 (2) Table Joins....................................................................................................................69 12 Database-Driven Web Applications...........................................................................................................70 12.1 Objectives......................................................................................................................................70 12.2 References......................................................................................................................................70 12.3 Overview........................................................................................................................................70 12.3.1 Servlet-based system with direct access to the database......................................................70 12.4 JDBC Driver Installation...............................................................................................................70 12.5 Setup Libraries...............................................................................................................................71 12.6 Create a Dynamic News Feed........................................................................................................71 12.6.1 web.xml................................................................................................................................74 12.7 Test .................................................................................................................................................74 12.7.1 News feed home page ...........................................................................................................74 12.8 Exercises........................................................................................................................................75 12.8.1 (1) Add news........................................................................................................................75 12.8.2 (2) PubDate field..................................................................................................................75 13 Database Connection Pooling.....................................................................................................................77 13.1 Objectives......................................................................................................................................77 13.2 References......................................................................................................................................77 13.3 Overview........................................................................................................................................77 13.4 Configure the DataSource..............................................................................................................77 13.4.1 publisher.xml........................................................................................................................77 13.5 Modify the News Feed Servlet......................................................................................................78 13.6 Create a ServletContextListener to do Initialization ......................................................................79 13.7 Test .................................................................................................................................................80 13.8 Exercises........................................................................................................................................80 13.8.1 (1) Anticipating problems....................................................................................................80 14 Data Access Objects.....................................................................................................................................81 14.1 Objectives......................................................................................................................................81 14.2 References......................................................................................................................................81 14.3 Overview........................................................................................................................................81 14.3.1 Servlet-based system with direct access to the database......................................................81 14.3.2 Servlet-based system with object-oriented approach to persistence....................................81 14.4 Create NewsItem Class..................................................................................................................82 14.5 Create DataAccessObject ...............................................................................................................83 14.5.1 DataAccessObject.java.........................................................................................................83 iv
Table of Contents
14 Data Access Objects 14.6 Create NewsItemDAO...................................................................................................................85 14.7 Modify the News Feed Servlet......................................................................................................87 14.8 Test .................................................................................................................................................88 14.9 Exercises........................................................................................................................................88 14.9.1 (1) PubDate field..................................................................................................................88 14.9.2 (2) Description field.............................................................................................................88 15 Item Management........................................................................................................................................89 15.1 Objectives......................................................................................................................................89 15.2 Chapter Contents ............................................................................................................................89 16 Item Management (continued) ....................................................................................................................90 16.1 Overview........................................................................................................................................90 16.1.1 Use Cases.............................................................................................................................90 17 Item Management (continued) ....................................................................................................................92 17.1 Interface Design.............................................................................................................................92 17.1.1 Page Flow Diagram..............................................................................................................92 18 Item Management (continued) ....................................................................................................................95 18.1 Page Design...................................................................................................................................95 18.1.1 Page Layout..........................................................................................................................95 18.1.2 Page Example.......................................................................................................................95 18.1.3 top.inc...................................................................................................................................97 18.1.4 middle.inc.............................................................................................................................98 18.1.5 bottom.inc.............................................................................................................................98 19 Item Management (continued) ....................................................................................................................99 19.1 System Architecture.......................................................................................................................99 19.1.1 Initial data model for the publisher application ....................................................................99 19.1.2 Layered architecture of the Publisher system .......................................................................99 19.1.3 Architecture based on Servlets, JSP and Data Access Objects..........................................100 20 Item Management (continued) ..................................................................................................................101 20.1 Home Page...................................................................................................................................101 20.1.1 Configure a new servlet in the deployment descriptor.......................................................101 20.1.2 Create HomeServlet...........................................................................................................101 20.1.3 Create JSP Files..................................................................................................................102 20.1.4 Test.....................................................................................................................................102 21 Item Management (continued) ..................................................................................................................104 21.1 List Page......................................................................................................................................104 21.1.1 Overview............................................................................................................................104 21.1.2 Modify the Deployment Descriptor...................................................................................104 21.1.3 Create ListNewsItemsServlet.............................................................................................104 21.1.4 Create JSP ...........................................................................................................................105 21.1.5 Test.....................................................................................................................................105 v
Table of Contents
22 Item Management (continued) ..................................................................................................................107 22.1 View Page....................................................................................................................................107 22.1.1 Overview............................................................................................................................107 22.1.2 Configure a New Servlet in the Deployment Descriptor...................................................107 22.1.3 Implement ViewNewsItemServlet.....................................................................................107 22.1.4 Create JSP ...........................................................................................................................108 22.1.5 Test.....................................................................................................................................108 23 Item Management (continued) ..................................................................................................................110 23.1 Edit Page......................................................................................................................................110 23.1.1 Overview............................................................................................................................110 23.2 Modify News Item DAO.............................................................................................................112 23.3 Modify Deployment Descriptor...................................................................................................113 23.3.1 Implement EditNewsItemServlet.......................................................................................113 23.3.2 Create JSP ...........................................................................................................................116 23.3.3 Test.....................................................................................................................................116 24 Item Management (continued) ..................................................................................................................118 24.1 Create Page..................................................................................................................................118 24.1.1 Overview............................................................................................................................118 24.1.2 Modify the news item DAO...............................................................................................118 24.1.3 Modify the Deployment Descriptor...................................................................................118 24.1.4 Create CreateNewsItemServlet..........................................................................................119 24.1.5 Test.....................................................................................................................................120 25 Item Management (continued) ..................................................................................................................122 25.1 Delete Page..................................................................................................................................122 25.1.1 Overview............................................................................................................................122 25.1.2 Modify the news item DAO...............................................................................................122 25.1.3 Modify the Deployment Descriptor...................................................................................122 25.1.4 Create DeleteNewsItemServlet..........................................................................................123 25.1.5 Create the JSP .....................................................................................................................124 25.1.6 Test.....................................................................................................................................124 25.2 Exercises......................................................................................................................................125 26 Item Management (continued) ..................................................................................................................127 26.1 Exercises......................................................................................................................................127 26.1.1 (1) Add link to list items page............................................................................................127 26.1.2 (2) Bad item id ....................................................................................................................127 26.1.3 (3) Multi-user problems ......................................................................................................127 26.1.4 (4) Reducing code duplication through inheritance...........................................................127 26.1.5 (5) Servlet initialization parameters...................................................................................127 26.1.6 (6) Graceful user error handling.........................................................................................128 27 Web Application Security.........................................................................................................................129 27.1 Objectives....................................................................................................................................129 27.2 Chapter Contents ..........................................................................................................................129
vi
Table of Contents
28 Web Application Security (continued).....................................................................................................130 28.1 Overview......................................................................................................................................130 29 Web Application Security (continued).....................................................................................................131 29.1 Configure HTTPS........................................................................................................................131 29.1.1 Overview............................................................................................................................131 29.1.2 Create Keystore with Self-Signed Certificate....................................................................131 29.1.3 Running keytool under Windows.......................................................................................131 29.1.4 Running keytool under Linux and Mac OS X ....................................................................131 29.1.5 Configuring Tomcat...........................................................................................................132 29.1.6 Test.....................................................................................................................................132 30 Web Application Security (continued).....................................................................................................134 30.1 The Persistent User Class .............................................................................................................134 31 Web Application Security (continued).....................................................................................................139 31.1 Login Functionality ......................................................................................................................139 31.1.1 How Authentication Works................................................................................................139 31.1.2 Login Servlet......................................................................................................................139 31.1.3 Create a Logout Servlet......................................................................................................142 32 Web Application Security (continued).....................................................................................................144 32.1 Security Filter..............................................................................................................................144 33 Web Application Security (continued).....................................................................................................147 33.1 Password Digests.........................................................................................................................147 33.1.1 Secure Digester Utility Class.............................................................................................147 34 Web Application Security (continued).....................................................................................................151 34.1 Exercises......................................................................................................................................151 34.1.1 (1) Persistent Sessions........................................................................................................151 34.1.2 (2) Class Hierarchy .............................................................................................................151 34.1.3 (3) Elimination of Redundant Code...................................................................................151 34.1.4 (4) User Account Management..........................................................................................151 35 Wiki Application Development .................................................................................................................152 35.1 Objectives....................................................................................................................................152 35.2 Chapter Contents ..........................................................................................................................152 36 Wiki Application (continued) ....................................................................................................................153 36.1 Overview......................................................................................................................................153 37 Wiki Application (continued) ....................................................................................................................155 37.1 Project Creation...........................................................................................................................155 37.2 Database Creation........................................................................................................................155 37.2.1 createdb.sql.........................................................................................................................155
vii
Table of Contents
38 Wiki Application (continued) ....................................................................................................................158 38.1 Persistence Classes .......................................................................................................................158 38.1.1 Overview............................................................................................................................158 38.1.2 Setup Logging....................................................................................................................158 38.1.3 Page Class ...........................................................................................................................158 38.1.4 Data Access Object Super Class........................................................................................160 38.1.5 The Page DAO Class ..........................................................................................................161 38.1.6 The Init Class ......................................................................................................................162 39 Wiki Application (continued) ....................................................................................................................164 39.1 View Page....................................................................................................................................164 39.1.1 Overview............................................................................................................................164 39.1.2 JSP......................................................................................................................................164 39.1.3 The View Page Servlet.......................................................................................................165 39.1.4 The Deployment Descriptor...............................................................................................167 39.1.5 Deploy................................................................................................................................167 39.1.6 Test.....................................................................................................................................168 40 Wiki Application (continued) ....................................................................................................................169 40.1 Edit Page......................................................................................................................................169 40.1.1 Overview............................................................................................................................169 40.1.2 The JSP...............................................................................................................................169 40.1.3 The Edit Page Servlet.........................................................................................................170 40.1.4 Modify Deployment Descriptor.........................................................................................172 40.1.5 Test.....................................................................................................................................172 41 Wiki Application (continued) ....................................................................................................................174 41.1 Publish Page.................................................................................................................................174 41.1.1 Overview............................................................................................................................174 41.1.2 The JSP...............................................................................................................................174 41.1.3 The Publish Page Servlet ....................................................................................................174 41.1.4 Modify Deployment Descriptor.........................................................................................176 41.1.5 Test.....................................................................................................................................177 42 Wiki Application (continued) ....................................................................................................................179 42.1 Unpublish Page............................................................................................................................179 42.1.1 Overview............................................................................................................................179 42.1.2 The JSP...............................................................................................................................179 42.1.3 The Unpublish Page Servlet...............................................................................................179 42.1.4 Deployment Descriptor......................................................................................................181 42.1.5 Test.....................................................................................................................................181 43 Wiki Application (continued) ....................................................................................................................183 43.1 Exercises......................................................................................................................................183 43.1.1 (1) Confirming Cancelations..............................................................................................183 43.1.2 (2) Exception Catching Filter.............................................................................................183 43.1.3 (3) Redirection ....................................................................................................................183
viii
Table of Contents
44 Web Services ...............................................................................................................................................184 44.1 Chapter Contents ..........................................................................................................................184 45 Web Services (continued)..........................................................................................................................185 45.1 Overview......................................................................................................................................185 46 Web Services (continued)..........................................................................................................................188 46.1 A Web Service to Publish News Items........................................................................................188 47 Web Services (continued)..........................................................................................................................193 47.1 Invocation of the Publish Service from the Wiki Application .....................................................193 48 Web Services (continued)..........................................................................................................................199 48.1 The Unpublish Service .................................................................................................................199 49 Web Services (continued)..........................................................................................................................203 49.1 Security Mechanisms...................................................................................................................203 49.1.1 Overview............................................................................................................................203 49.1.2 Public/Private Key Pair......................................................................................................203 49.1.3 Create Truststore................................................................................................................204 49.1.4 Modify Deployment Descriptor.........................................................................................205 49.1.5 Authenticating Clients........................................................................................................205 49.1.6 Test.....................................................................................................................................208 50 Web Services (continued)..........................................................................................................................212 50.1 Exercises......................................................................................................................................212 50.1.1 (1) Handling Failures ..........................................................................................................212 50.1.2 (2) News Item Quotas .........................................................................................................212 51 Conclusion..................................................................................................................................................213 51.1 Overview......................................................................................................................................213 52 Contents......................................................................................................................................................214 53......................................................................................................................................................................216
ix
1 Preface
1.1 Overview
This is a free online book developed by Dr. David Turner of California State University San Bernardino and Dr. Jinseok Chae of University of Incheon. The purpose of the book is to introduce students to web application development in Java with the use of Eclipse. The book assumes a familiarity with HTML and the Java programming language. The book is in cookbook format in that it provides instructions on how to construct solutions to various problems. The intent is to show students how to accomplish typical Web development tasks in the Java language. In later chapters of the book, detailed instructions are omitted if they duplicate instructions in an earlier chapter. This assumes the student can recall or refer back to the previous instructions. Unguided exercises are also provided so that students can apply what they have covered in the main text. The book omits many details and explanations. For these, the reader will need to consult online documentation or search the Web for other tutorials and articles. Each chapter contains a list of references that the reader may find useful for filling in these missing details.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 06, 2009 01:47 pm
1 Preface
2.2 Overview
The term web application refers to a software system that provides a user interface through a web browser. Examples of web applications include blogs, wikis, online shopping, search engines, etc. Web application development became an important discipline following the adoption of the Internet by ordinary users. Many businesses now rely heavily on the web for both internal applications and to provide services to customers, and so there are many employment opportunities open to individuals with web development skills. Web sites can be roughly classified as static or dynamic. Static web sites are those sites that use a web server to provide access to HTML documents that are stored in the file system. Dynamic web sites are those sites that construct the content of web pages from data that is stored in a database. The databases on which these dynamic sites are built are typically modified as a result of user interaction with site. Thus, users are presented with web pages that are uniquely generated for them based on their previous interactions with the site. The trend is for web pages to be generated from databases rather than being read from the file system.
The above line of code can be simplified by importing the class java.net.Socket into the local namespace by adding the following line just after the package declaration of a java source code file.
import java.net.Socket;
The above import statement allows for the following simplified version of the socket creation code give above, in which the package prefix qualifiers are dropped from the Socket class. 2 Introduction to Java Web Application Development 2
2.11 Ant
Ant is the Java version of the make utility that is commonly used to build programs written in C or C++. Without an IDE such as Eclipse, a Java programmer would normally write ant build scripts to perform repetitive tasks, such as compiling and packaging compiled code into archives (jar files). With an IDE such as Eclipse, programmers can invoke commonly used operations such as building through the GUI of the IDE. However, there will always be a need to develop scripts in non-trivial projects to automate repetitive tasks. For this reason, this book covers the use of ant for running database regeneration scripts and for generating various objects needed for application security. Ant is built into Eclipse, so the user can run ant build scripts through the Eclipse menu system. Ant build scripts are in the form of XML files. The default name of a build file is build.xml. The build file contains one or more targets, each of which perform some job. Each target is comprised of any number of tasks, which comprise the atomic actions that a user can specify. Ant is a free, open source project maintained by the Apache Software Foundation. The ant build system is well documented, and there are numerous tutorials and articles on its use. This book employs ant in a simple way, so that students can become familiar with its use and the syntax of an ant build file.
Java Web Programming with Eclipse expression of the application's business logic. This book focuses on an approach to web application design that is based on persistent objects.
2.13 Security
In the Java Web development world, there are several ways to implement security features in an application. This book uses a simple approach to authentication and authorization. A unified process of validating user input is also presented.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 06, 2009 01:21 pm 2.12 Web Application Architecture 6
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 06, 2009 01:26 pm
4 Java Setup
4.1 Objectives
To install Java in your development environment
4.2 Overview
All Java code runs inside a Java Virtual machine (JVM). The system that provides the JVM is referred to as the Java Runtime Environment (JRE). A JRE is sufficient to run Java code, but it does not contain software development tools needed by developers. For this reason, we need to install the Java Development Kit (JDK), which contains both a runtime environment and developer tools. Sun provides the JDK in two forms: a Java 2 Standard Edition (J2SE), and a Java 2 Enterprise Edition (J2EE). The J2EE contains the J2SE within it, but also provides additional libraries, additional tools, and a J2EE Application Server. For the purposes of this book, we only need the J2SE JDK.
4.3 Installation
If Java is not already installed on your system, then you should go to Go to Sun Developer Network and locate the download page for the most recent release of the Java Standard Edition (SE) Software Development Kit; at the time of this writing, this was titled Java SE Development Kit (JDK) 6 Update 11. Download and install this package. Optionally, you can install the documentation titled Java SE 6 Documentation. Alternatively, you can simply access Sun's online version of the JDK 6 Documentation. The most important part of the documentation is the Java Platform API Specification.
4.4 Exercises
4.4.1 (1) Test Installation
Test your installation by running the java command with the version option. To do this, obtain a command prompt and execute the following.
java -version
4.5 Notes
Later procedures in the book may require creating an environmental variable called JAVA_HOME. Also, modifying the PATH variable may also be needed.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 07, 2009 08:18 am
4 Java Setup
4.5 Notes
10
5 Eclipse Setup
5.1 Objectives
To install Eclipse in your development environment Learn how to modify the default behavior of Eclipse by associating new file types with the text editor
5.2 Overview
Eclipse is a tool for building software projects. Such a tool is also referred to as an integrated development environment, or simply IDE. Eclipse is similar to Microsoft Visual Studio, except that it is free and open source. IBM started eclipse as a proprietary, closed source project. However, after reaching a fairly advanced state of development, IBM converted eclipse into a free, community-supported open source project. The development of eclipse is now managed by the Eclipse Foundation, which is a non-profit organization. Eclipse can be easily extended by any programmer. Eclipse comes with extensive documentation on how to do this. This is one of the reasons eclipse has gained in popularity. You can extend eclipse in one of two ways: by adding plug-ins, or by adding collections of plug-ins called features. Eclipse is written in Java, and is primarily used as a tool to build Java projects. However, eclipse can be used to build projects in any language.
5.3 Installation
If Eclipse is not already installed on your system, go to the Eclipse website and download and install the Eclipse IDE for Java Developers. There is no installation program for Eclipse. Instead, unpack the compressed archive that you downloaded and unpack into a convenient location. You launch Eclipse by running the Eclipse executable file.
5.4 Issues
5.4.1 64-Bit Windows
Eclipse does not run (or does not run well) with a 64-bit JVM on Windows. If you are running 64-bit Windows, then install 32-bit Java and run Eclipse with it. If eclipse is still not launching correctly for you, it may be that it is loading a 64-bit version of Java. You can tell eclipse which JVM to use by adding the -vm argument to eclipse.ini and have it point to 32-bit Java. The following is an example eclipse.ini file that corrects this problem.
-showsplash org.eclipse.platform --launcher.XXMaxPermSize 256M -vm "C:\Program Files (x86)\Java\jdk1.6.0_11\bin\javaw.exe" -vmargs -Dosgi.requiredJavaVersion=1.5
5 Eclipse Setup
11
5.6 Exercises
12
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 13, 2009 11:37 am
13
6.2 Overview
Tomcat is a J2EE Web Container, which means it is a Web server and a platform to run Java Servlets and JSP. Tomcat is an open source project managed by the Apache Software Foundation. This chapter guides you through the installation of Tomcat, explains Tomcat class loading issues, and shows how to perform a deep restart of Tomcat.
If you downloaded the Windows service installer, then run it to install Tomcat. Otherwise, follow the instructions in the distribution or on the tomcat web site to install tomcat on your system. In this book the folder in which tomcat is installed is referred to as ${TOMCAT_HOME}.
6.4 Test
After installation is complete, test that everything is OK. Under Windows run Configure Tomcat, which is found through the Start menu. After starting Tomcat, go to the the following url in a browser to see if tomcat is running.
http://localhost:8080/
14
6.5 Issues
6.5.1 Tomcat doesn't start under Vista
If you installed Tomcat as a service, you need to run Tomcat as administrator. Right click on the Tomcat Configuration in the start menu and select Run as administrator.
[info] Procrun (2.0.4.0) started [info] Running Service... [info] Starting service... [174 javajni.c] [error] The specified module could not be found. [994 prunsrv.c] [error] Failed creating java C:\Program Files\Java\jre6\ [1269 prunsrv.c] [error] ServiceStart returned 1 [info] Run service finished. [info] Procrun finished.
If this is your case, then the problem is that msvcr71.dll is not being loaded. The solution is to add the folder that contains this dll to your Path. For example, if the Java binaries are in C:\Program Files\Java\jre6\bin, then append the following onto your system Path. (Path is an environmental variable, which you can modify through Control Panel.) Modify this example path to point to the location of the Java binaries in your system. 6.4 Test 15
You may need to restart your system (or logout/login) in order to make changes to the Path variable effective. If you are using more than one version of Java, then adding Java to the Path variable is not advised because other applications may not run correctly. One possible solution is to start tomcat with something like the following.
cd C:\Users\User\apache-tomcat-6.0.18\bin set JRE_HOME=C:\Program Files (x86)\Java\jre6 startup.bat
16
Notice there are currently 4 Web applications deployed to the server. In the column labeled Path, you can see the Context Path for each application. For service requests (from Web browsers, or other clients) to reach a particular Web application, the client must include the context path within the URL it uses to reach the server. Web service URLs are comprised of four pieces of information: the protocol (which is http), the fully qualified DNS hostname (which is localhost for the local machine), the port number on which the web service is listening (which is 8080 in the default configuration of Tomcat), and a pathname to a particular service (which is /manager/* for various services available through the manager application). For example, to reach the home page of the manager application currently running in your machine, you would use the URL http://localhost:8080/manager. In this book, you will use the manager application to deploy, start, stop, and reload web applications.
17
Under the Reference section, follow the link to the Servlet API Javadocs. These javadocs (API documentation generated from the source code using the javadoc tool) describe the API of the programming environment in which you will be working.
18
Under Windows, there is an Eclipse plug-in called Logwatcher that enables similar functionality. The next section explains how to install and use LogWatcher.
6.9.1 Overview
19
6.11.1 Overview
Sometimes it is necessary to perform a deep restart of Tomcat, which means to delete all of Tomcat's generated files, which are stored in the work directory. These files include JSP translated into source code and their corresponding class files. These files also include other derived objects related to the configuration of tag libraries and other features. Difficult-to-find bugs will occur when the generated files in the work directory are not synchronized with the files comprising the installed web application. If you suspect that this condition may be causing problems at some point, you can force Tomcat to regenerate all files in the work directory, which is a procedure that we refer to as a deep restart of Tomcat.
6.12 Exercises
6.12.1 (1) Servlet API
Locate and study the documentation for the HttpServlet class.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 21, 2009 05:56 am 6.11.1 Overview 20
21
7 Java Servlets
7.1 Objectives
Learn the organization of files for Java web applications Learn how to create a Java project in Eclipse to develop a Web application Learn how to write and run servlets Learn how to deploy a web application in Tomcat Learn how to attach source code for libraries Learn how to turn off compiler warnings Learn how to use the Organize Imports feature of Eclipse to resolve class names conveniently
7.2 References
The J2EE 1.4 Tutorial (See Chapter 11.) J2EE 1.4 API HTML 4.01 Specification W3 Schools HTML Tutorial
7.3 Overview
This section guides you through the creation of a Java servlet. The instructions in this section show you how to write the servlet in Eclipse and deploy it to the Tomcat web server. Actually, Tomcat is also classified as a web container, or servlet container, because servlets are placed inside a running instance of Tomcat. The servlet that we create in this section simply generates a Web page that says Hello, World! This simple exercise will help you understand the basic structure of servlets, how to develop them in Eclipse, and how to deploy them in Tomcat. If you have trouble using Eclipse commands in this chapter, you may want to go through the following two tutorials that are built into Eclipse and accessible through the Eclipse help menu. Workbench Basic Tutorial Java Development Basic Tutorial
7 Java Servlets
22
Java Web Programming with Eclipse 5. Under Project Layout, make sure that the box next to Create separate source and output folders is checked. 6. Click the Next button. 7. Select the Source tab. 8. Set the Default output folder to website/web/WEB-INF/classes. The following screenshot shows the screen at this point.
9. Select the Libraries tab. 10. Click the Add External JARs button. 11. Navigate to ${TOMCAT_HOME}/lib. 12. Select servlet-api.jar and click the Open button. 13. Click the Add External JARs button. 14. Select jsp-api.jar, and click the Open button. (Adding jsp-api.jar is optional at this point, but will be used later when developing custom JSP tags.) The following screenshot shows the screen at this point.
23
Java Web Programming with Eclipse 5. Select External File and navigate to and select the Tomcat source code zip file that you downloaded in the first step. 6. The following screen shot shows the result. 7. Click OK to complete the operation.
Java Web Programming with Eclipse 1. Expand the web folder. 2. Right-click on the WEB-INF folder and select New ... File. 3. Specify a name of web.xml and click the OK button. 4. In the text editor window that appears for web.xml, insert the contents of the following code listing, and save the file. If you can not edit the web.xml file in the window that Eclipse provides, it is because Eclipse is using the XML editor to provide access to the file. Close this window and right click on web.xml in the Project Explorer view and select Open With ... Text Editor.
Note: make sure there is no leading space in the web.xml file. In other words, the file should start with <?xml version="1.0"?> without any space before the left angle bracket. The url-pattern /home is relative to the context path that identifies the website Web application. Although we haven't specified this yet, the context path will be /website. This means, for a browser to invoke the home servlet, it must request the following URL.
http://localhost:8080/website/home
The deployment descriptor can be used to tell tomcat many things. However, the most basic information provided in a deployment descriptor are the servlets and their associated url patterns. For each servlet in your web application, there should be a servlet element, such as the following.
<servlet> <servlet-name>home</servlet-name> <servlet-class>website.web.HomeServlet</servlet-class> </servlet>
The above servlet element tells the web container to create an instance of website.web.HomeServlet and call that instance by the name home. Although it is possible to create additional instances of HomeServlet, normally a single instance is made. In addition to creating servlet instances, the web container should associate url patterns with these instances, so that when the web container receives an HTTP request from a web browser, it can determine which servlet to use to process the request. The following servlet-mapping element in our deployment descriptor tells 7.6.1 Deployment Descriptor web.xml 26
Java Web Programming with Eclipse tomcat that all incoming requests for home should be processed by the servlet instance with name home.
<servlet-mapping> <servlet-name>home</servlet-name> <url-pattern>/home</url-pattern> </servlet-mapping>
Multiple servlet-mapping elements can be used to associate any number of url patterns with a single servlet instance.
27
7. Click the Finish button. Notice that there is a warning icon in the HomeServlet file next to the line starting with public class HomeServlet. If you hover over the warning icon with the mouse pointer, Eclipse will display a short description of the warning, which is that you have not declared a field called serialVersionUID. This warning is generated for every class the implements the Serializable interface, but that does not contain a serialVersionUID field. However, for our purposes, creating field serialVersionUID is not necessary. To turn off this warning, do the following. 1. Select Window ... Preferences. 2. Select Java ... Compiler ... Errors/Warnings. 3. Select Potential programming problems. 4. Use the dropdown box to Ignore Serializable class without serialVersionUID. The following screen shot shows the result of carrying out steps 1 through 4.
28
5. Click the OK button, and click the Yes button to do a full rebuild. Now, we override the doGet() method we inherit from the parent class. In the HomeServlet.java file, do the following. 1. Select Source ... Override/Implement methods. 2. Select the doGet() method by checking the appropriate checkbox. The following screen shot shows the result of carrying out steps 1 through 2.
29
1. Click the OK button. 2. Replace the body of the doGet method with the following code.
PrintWriter writer = resp.getWriter(); writer.println("<h1>Hello, World!</h1>");
1. The following screen shot shows the result of carrying out the previous step.
30
When you enter this code, observe the red error icon on the left-hand side of the window. You can read the error message by hovering over the icon with the mouse as shown in the following screen shot.
31
The error message in this case is that certain classes "cannot be resolved to a type." You can either fully qualify the class names with their package names, as in java.io.PrintWriter, or you can identify the package location of the classes with an import statement. The standard practice is to use import statements. Adding import statements are easy with Eclipse. To add the imports to HomeServlet, do the following.
Select Source ... Organize Imports.
Notice the asterisk (*) before the name HomeServlet.java in the window's tab. This indicates that changes to the file have not yet been saved. Save the file, and observe the disappearance of the asterisk. The following listing shows the HomeServlet.java file.
7.7.1 HomeServlet.java
package website.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException;
7.7.1 HomeServlet.java
32
Go to the manager application and locate the section called Deploy. Set the context path to /website. (Use a forward slash regardless of whether you are working in Windows, Linux or Mac.) Set the XML Configuration file URL to the following, where ${WORKSPACE} is the path to your Eclipse workspace. (Convert the back slashes to forward slashes if you are working under Linux or MacOS.)
${WORKSPACE}\website\website.xml
Click the Deploy button and then inspect the message section at the top of the manager application web page. If you see the following message, then you need to debug.
FAIL - Failed to deploy application at context path /website
If the application failed to start, you should check to make sure the path to website.xml is valid. You may also want to open the various tomcat log files and search for an error message that can give you a clue to solve the problem. If the manager application reports successful deployment, the next step is to verify that the application is working correctly by going to http://localhost:8080/website/home in your browser. If you make changes to Java code in a project, the changes will not be immediately deployed. To see the changes, you should reload the application through the manager application. If you make changes to the deployment descriptor (web.xml) in a project, reloading the application will not work. Instead, you need to stop and then start the application, which you can do in the manager application.
33
7.9 Exercises
7.9.1 (1) Servlet Mapping Element
Add an additional servlet mapping element to the deployment descriptor that associates the home servlet with the url pattern index.html. Test that the home servlet can be reached in the following 4 different ways. http://localhost:8080/website/home http://localhost:8080/website/index.html http://localhost:8080/website/ http://localhost:8080/website
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 10, 2009 01:31 pm
7.9 Exercises
34
8.2 References
Log4j Wiki
8.2.1 Overview
Software developers usually spend a lot of time debugging code. There are several techniques that you can use to find bugs. One technique is to use a debugger, which is a service normally provided by an IDE. With a debugger the developer can step through code one statement at a time as the program executes and inspect that state of variables. For this process to work, the IDE needs to control the execution of the program. When developing a desktop application, you can launch its execution inside Eclipse, set breakpoints, step through the code and inspect the state of variables. However, this procedure is not available to us because Eclipse does not control execution of our code; tomcat controls execution of the code. In order to have these capabilities, we would need to have Eclipse control the execution of Tomcat. One way to do this is to extend Eclipse functionality by installing the Eclipse Web Tools feature. However, we will not cover this option in this book. Another technique that is useful for debugging is trace statements. In this case, we insert statements at various points in the code to print out useful information. When this output goes into a file, it is called a log file. One of the benefits of using logging is that logging statements can be left in production code, so that log files are generated in the production environment. This enables the developer to diagnose bugs that surface in the production environment. Rather than simply using the basic print facilities, a logging framework provides a developer with the ability to set different logging levels, so that logging can be more or less verbose depending on the situation. For example, when the code is running in the production environment, you will most likely record error events rather than the fine details that would be useful to debug a known bug. There are two main choices of logging frameworks when working in Java: log4j and Java logging API. Log4j is the older of the two and is more widely used than the Java logging API. However, the Java logging API provides the same basic functionality as log4j. We will illustrate the use of the log4j logging framework in this chapter. In this chapter, you will add logging to the website application you started in the chapter on servlet basics.
Java Web Programming with Eclipse classpath of the deployed application by creating the folder lib under web\WEB-INF, and then copy the jar file into the lib folder. If you create the folder and copy the file inside Eclipse, then you are done. This is the approach that will give you the fewest problems. However, if you do either operation outside Eclipse, then you need to synchronize Eclipse with the file system by selecting File ... Refresh. To place the jar file on the classpath used for building, right click on the log4j jar file in the package explorer view of Eclipse and select Build Path ... Add to Build Path. In the Project Explorer view of Eclipse, the jar file will no longer be visible under the WEB-INF/lib folder; it now appears under the referenced libraries folder. Note that the Project Explorer view presents a logical view of your project rather than a physical view (file system view). The following screen shot shows the result of the above procedure. 8.2.2.1 Add the Log4j library to Build Path
36
37
Switch back to Java perspective in a similar manner. Also, there are icons in the upper right hand corner of the screen that can be used to speed up perspective switching.
38
Notice the error icons indicating that the identifier Logger can not be resolved to a type. Hold down the control and shift keys, and press the O key to organize imports. Because there are two packages in the classpath that contain classes called Logger, Eclipse presents them to you as choices as shown in the following screen shot. The one you should select is org.apache.log4j.Logger. 8.2.5.2 Organize Imports window
39
Add the following line of code to the doGet method of HomeServlet, which prints a logging message every time the doGet method runs.
logger.debug("Returning website");
The following program listing shows the modified HomeServlet.java file. 8.2.5.3 Modified HomeServlet.java for logging
package website.web; import java.io.IOException; import java.io.PrintWriter; import import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; org.apache.log4j.Logger;
public class HomeServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer=resp.getWriter(); writer.println("<h1>Hello, World!</h1>"); logger.debug("Returning website"); } }
After making changes to the home servlet, you need to reload the website application in the manager application so that Tomcat reloads the class definition of the servlet. 8.2.5 Modify HomeServlet 40
Java Web Programming with Eclipse In order for the website log file to get created, we need to write something into it. Do this by sending a request to HomeServlet by following the link http://localhost:8080/website/home. Observe that the file ${TOMCAT_HOME}/logs/website.log gets created. Open the log file in whatever log file viewer you are using and then reload the webpage in the browser window to see the logging message generated with each reload. The following screen shot shows the results in the LogWatcher window. 8.2.5.4 Observe the logging output in LogWatcher window
If you don't see the logging statement appear in the watch window, then try reloading the website application in the manager application.
8.3 Exercises
8.3.1 (1) Attach Source Code
Attach the source code for the log4j library. Refer to instructions given earier for attaching the source code for servlet-api.jar. 8.2.5 Modify HomeServlet 41
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 10, 2009 02:04 pm
42
9.2 References
The J2EE 1.4 Tutorial (See Chapters 12 and 13.) JSP 2.0 Syntax Reference
9.3 Overview
Java Server Pages (JSP) is the technology used in Java web applications to mix HTML and Java code similar to the way it is done in PHP and ASP. JSP pages are files that end with a jsp extension and contain a mixture of HTML, blocks of Java code (called scriplets) and other expressions. These JSP files are translated by JSP interpreters into Java source code. The resulting source code is then compiled, resulting in class files that can be loaded and executed by a Java virtual machine. The process is illustrated by the following diagram.
The benefit of JSP is that it allows one to easily mix HTML with Java code. For example, consider the following servlet.
package website.web; import import import import import import import java.io.IOException; java.io.PrintWriter; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; java.util.Date;
public class TestServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Date now = new Date();
43
You can accomplish the same result as the above code with the following JSP file.
<%@ page import="java.util.Date" %> <html> <body> <% Date now = new Date(); out.println(now); %> </body> </html>
JSP files can be used to process browser requests directly. To see how this is done, create a file called now.jsp in the web folder of the website project with contents equal to the code given above. Then go to http://localhost:8080/website/now.jsp and verify that the browser displays the current time and date. The first time you try to access a JSP file, the web container will translate the file into Java source code, compile the source code, load the new class into JVM memory, and execute the service method of the resulting class. This process takes some time, so there is usually a noticable delay the first time you access a JSP page. Subsequent requests for the file will be processed more quickly because the container directly invokes the service method of the class that was generated and loaded into memory the first time the file was requested. You can examine the source and byte code files that Tomcat generates from the JSP by looking within the following directory.
${TOMCAT_HOME}\work\Catalina\localhost\website\org\apache\jsp
Open the file now_jsp.java in a text editor such as Notepad. The class now_jsp is declared as follows.
public final class now_jsp extends org.apache.jasper.runtime.HttpJspBase ...
If you look up the documentation for org.apache.jasper.runtime.HttpJspBase you will see that this class is a subclass of HttpServlet. That means our now.jsp file was translated into a servlet. In fact, all JSP files are translated into servlets. Examine the body of the _jspService method within the now_jsp class. In particular, look at the out.write statements in the body of this method. Notice that the content of these lines roughly corresponds to the contents of now.jsp. When the translator encounters ordinary HTML content in a JSP file, it generates a write statement to send this content into the output stream directed to the browser. For example, the <body> tag in now.jsp is translated into the following Java statement.
out.write(" <body>\r\n");
The character symbols '\r' and '\n' represent carriage return and line feed, respectively.
9.3 Overview
44
Java Web Programming with Eclipse When the translator encounters JSP tags (tags with the format <% ... %>), it processes the contents of these tags rather than simply writing them into the output stream. Observe that the following two lines of Java code in the sample JSP appear embedded within the translated result.
Date now = new Date(); out.println(now);
9.4.1 home.jsp
<jsp:useBean id="message" scope="request" class="java.lang.String" /> <html> <head> <title>website</title> </head> <body> <h1>Home</h1> <p> <%=message%> </p> </body> </html>
The first line in the above JSP file is a useBean element. The useBean element will generate code that attempts to locate an instance of a Java class (called a bean in this context) with the name message in something called request scope. What this means is that it tries to find a value that is associated with the key "message" in the HttpServletRequest object that the web container created for handling of the current request. Thus, HttpServletRequest is an associative array, which is also called by the terms map or dictionary. If useBean doesn't find the key "message" in the request object, then it creates an instance of java.lang.String by calling its no-argument constructor. In general, useBean will create an instance of the class specified by its class attribute if the object is not found in the request map. Next, we modify the HomeServlet so that it creates a String and places it into the request object that gets passed into the home.jsp. In this way, the servlet controls the data that the JSP file presents. This is the general pattern that is followed by MVC-based architectures, which is also referred to by the term multi-tiered architectures.
45
We will set the value of homeJsp in the Servlet's init() method. To do this, do the following. 1. Select Source ... Override/Implement Methods. 2. Expand the branch for the class GenericServlet. 3. Check the box next to the init(ServletConfig) method. 4. Set the insertion point to First Member (or First Method). (This will insert the new method before doGet, which helps to document the workflow through the class in the sense that init is called first and only once.) The following screen shot shows the result of carrying out steps 1 through 4. 5. Click the OK button.
The init method runs the first time the web container loads HomeServlet, therefore it is the logical place to put initialization code. We will use the init method to create a RequestDispatcher that will be used to run home.jsp. To do this, replace the body of the init method with the following (and organize imports).
ServletContext context = config.getServletContext();
46
The following sequence diagram illustrates the flow of execution resulting from a browser request for the home page of the website application.
When the user issues the command in his browser to retrieve the home page, the browser establishes a TCP connection with the server and uses this to send an HTTP GET request to the web server. When Tomcat gets the incoming GET request, it parses the HTTP request message and finds that the browser is requesting a resource by the name /website/home. Tomcat uses the url-pattern elements in the web.xml file to determine how to process these requests. In this case, the requested resource matches with the url-pattern associated with the home servlet. As a result, Tomcat invokes the doGet method of the home servlet. The home servlet sets an attribute (with key message) in the request object passed to it by Tomcat, and then forwards execution to homeDispatcher, which passes control to home.jsp. Finally, home.jsp generates the HTML content that is returned to the browser within an HTTP response message. After the browser receives the HTML, it closes the TCP connection with the server. The following listing shows the modified HomeServlet.java file. 9.4.2.1 Modified HomeServlet.java for JSP
package website.web; import java.io.IOException; import import import import import import javax.servlet.RequestDispatcher; javax.servlet.ServletConfig; javax.servlet.ServletContext; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest;
47
Notice in the doGet method of HomeServlet that we pass the value of message through the HttpServletRequest object req. As stated earlier, HttpServletRequest acts as a map that associates keys (message in this case) with values (bye in this case). The expression <%=message> in the JSP is used to insert the value associated with "message" within the HTML that is sent to the browser. The expression <%=message> is approximately equivalent to the following.
String message = req.getAttribute("message"); outputStream.write(message);
9.4.3 Test
Reload the website application with the Tomcat manager application. Then, go to http://localhost:8080/website/home to verify that your code is working correctly. Also, check the logging window for the new logging message. The the next two screen shots show the web page generated by the JSP and the output of the logging window.
9.4.3 Test
48
9.4.3 Test
49
In general, Tomcat will monitor the timestamps on the JSP files in order to detect changes. When a JSP file changes, Tomcat will re-translate the files, so you do not need to explicitly reload an application after making changes to the JSP. For changes to servlet code and other Java code in your project, you need to reload the application through the manager application.
9.5 Exercises
9.5.1 (1) Methods doGet and doPost, Revisited
Rework your solution to exercise 1 in the servlet chapter so that Your solution follows the model-view-controller pattern presented in this chapter.
9.5 Exercises
50
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 24, 2009 12:11 pm
51
10.2 References
RSS Tutorial ROME JDOM
10.3 Overview
People interpret the acronym RSS in several ways. For example, you may hear that RSS stands for Rich Site Summary, or Really Simple Syndication, or even RDF Site Summary. Most people simply refer to the technology as RSS. In all cases, RSS is a protocol for providing news summaries in XML format over the Internet. The following is an examlpe of an XML document that is a news feed. It contains a root element called rss. Under the rss element, there is a single child element called channel. The title, description and language elements within the channel element are properties of the entire news feed. Following these elements are a sequence of zero or more item elements. Each item element represents a summary of a news story. In our example, we include for each news story item, the title of the news article, a link to the web page with the complete new article, and a short description of the article.
<rss version="2.0"> <channel> <title>My News</title> <description>This is my news</description> <language>en-us</language> <item> <title>Hello</title> <link>http://csusb.edu/</link> <description>Hello there.</description> </item> <item> <title>Bye</title> <link>http://cse.csusb.edu/</link> <description>Come here, go any where.</description> </item> </channel> </rss>
In this chapter, we incorporate a news feed provided by yahoo in the home page of our website application. The following diagram illustrates the flow of information that will take place.
52
First, the user issues the command to his browser to retrieve the home page of the website application. In response, the browser sends an HTTP GET request to the website application to request the home page. The website application sends an HTTP GET request to the yahoo news feed server to request a current summary of news. The yahoo news feed server returns to the website application an XML document (in RSS format) that contains a list of news items. The website application parses the XML document to extract the news items. It then uses this information to construct the HTML that it returns to the browser.
53
After replacing the body of doGet with the new code you will get icons indicating compilation errors. Most of these errors are due to the fact that the class names being used are not fully qualified (prefixed by their package names) or not imported in the import section at the top of the file. To fix this problem, you should invoke the organize imports operation in the source menu. However, when you do this, eclipse will not be able to determine the package for the InputStream class, because several different packages include an InputStream class. Eclipse will present to you a list of possible fully qualified class names to choose from. The following list shows the choices you should make in this step. 1. com.sun.syndication.io.XmlReader 2. java.net.URL After organizing imports, there will still be a compilation error. In particular, there will be an error icon identifying a problem with the following line.
syndFeed = syndFeedInput.build(xmlReader);
If you hover the mouse pointer over the error icon, you will see that there is an unhandled Exception of type FeedException. Use Eclipse to generate exception catching code by doing the following. 1. Highlight the entire line that is marked with the error. 2. Select Source ... Surround with ... Try/catch block. Eclipse generated two catch phrases: one to catch an IllegalArgumentException, and another to catch a FeedException. The code invokes the printStackTrace method of the caught exception. This method will print a stack trace to the standard output stream (System.out). However, in our code, we want to report these and other exceptions in the application log file. To do this, replace the lines that invoke the printStackTrace method with the following.
logger.error("", e);
54
Whenever the doGet method of the HomeServlet is invoked, the servlet requests a news feed from yahoo related to technical news. The servlet uses the SyndFeedInput class of the ROME library to parse the RSS document into a SyndFeed object. The SyndFeed interface allows us to conveniently access the information in the news feed using standard Java idioms. The servlet exposes the SyndFeed object to the JSP by placing it in request scope with the setAttribute method of the request object. After doing this, it passes execution to the JSP, which will extract the news data from the SyndFeed object and embed it into the HTML that it returns to the browser.
55
The code in our JSP file includes references to classes, such as SyndFeed, that need to be either fully-qualified or imported. In our example code, we import these names by using a JSP tag that starts with <%@ page import=... These lines tell the JSP translator which Java imports it needs to include in the code that it generates. For example, the JSP translator will translate the first line in the previous listing to the following.
import com.sun.syndication.feed.synd.SyndFeed;
You can confirm this by looking in the file home_jsp.java under ${TOMCAT_HOME}/work.
10.6 Test
Test your application by reloading the website application in the the manager application and going to http://localhost:8080/website/home.
56
Within the web directory, create a new file called news.rss with the following contents.
<rss version="2.0"> <channel> <title>My News</title> <description>This is my news</description> <language>en-us</language> <item> <title>Hello</title> <link>http://csusb.edu/</link> <description>Hello there.</description> </item> <item> <title>Bye</title> <link>http://cse.csusb.edu/</link> <description>Come here, go any where.</description> </item> </channel> </rss>
Deploy the publisher application in the same manner that you deployed the website application and verify that you can access news.rss through your browser by going to http://localhost:8080/publisher/news.rss. Finally, modify the url in the website project so that it points to your news feed in the publisher application. Verify that the website application is now displaying your news through the following link: http://localhost:8080/website/home. Remember to examine your log files if the application doesn't work as expected. Note that the website application is communicating with the publisher application by sending XML over HTTP. This inter-application communication is a form of web services, and applications built in this way are said to follow a service-oriented architecture.
10.8 Exercises
10.8.1 (1) Include someone else's news
Modify the URL in HomeServlet so that you include another student's news into your home page.
57
Java Web Programming with Eclipse Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 13, 2009 11:28 am
58
11.2 References
MySQL Ant
11.3 Overview
This chapter describes the installation and use of the MySQL database server for use in Java Web applications. MySQL is a free, open source database server that has been in development since 1995. Over the years it has matured significantly so that it is now widely known and relied on as a backend service for Web applications.
59
The above setting causes the mysql server to reject TCP connections that are not from the computer with IP address 127.0.0.1, which is the IP address that operating systems assign to the local machine.
11.4.3 Test
After installation is complete, test that everything is OK. In Windows, run the MySQL command line client through the start menu. On Linux, Mac or Windows, you can run the mysql command line client from a command prompt with the command mysql -u root -p. Enter the password that you specified during 11.4 Install MySQL 60
Java Web Programming with Eclipse installation. The mysql prompt appears as shown in the following figure.
The MySQL command line client is a program that allows the user to submit standard SQL commands to the database server and view the results. It also allows the user to submit non-SQL commands that are uniquely supported by MySQL. In a web application, you will specify these commands as strings in your java code, and submit them to the database through the JDBC database abstraction layer. To test that the server is running, enter the following command at the mysql prompt and press the enter key. Note that the command is terminated with a semicolon, which is a detail that you should remember to perform on all the database commands.
mysql> show databases;
11.4.3 Test
61
Java Web Programming with Eclipse As you can see, the show databases command resulted in a table with a single column. The column heading includes the name Database and the three rows under it show the names of the three databases that were created by the installation program. In general, when a command produces a response, the response will be formatted as a table.
11.5.2 Quit
The following command terminates the mysql command line client.
mysql> quit;
This command tells MySQL to use the db_name database as the current database for subsequent commands.
62
This command creates a table with the given name and column definitions. A column definition includes a column name, a data type and optional attributes (unique, not null, etc.).
This command deletes a table. All table data and the table definition are removed, so be careful with this command!
These commands show different ways to retrieve data from a single table. The asterisk in the first and second examples indicates that data is to be retrieved from all columns in the table, whereas the third example lists the columns from which data is to be retrieved. The first and third examples retrieve data from every row in the table, whereas the second example retrieves data only from rows in which col_name1 has the specific value col_value1. In a later chapter, we explain how to use the select command to retrieve data from multiple tables.
11.6.5 Examples
The following examples illustrate the commands described previously. In each example, we show the command that is submitted at the mysql prompt and the result that is displayed to the user.
63
Java Web Programming with Eclipse Create a new database called bookstore.
mysql> create database bookstore; Query OK, 1 row affected (0.03 sec)
Make the bookstore database the current database on which all subsequent commands will operate.
mysql> use bookstore; Database changed
Within the bookstore database, create a table called book with 3 columns. The name of the first column is id and its data type is integer. The name of the second column is title and its data type is variable-length string with a maximum of 40 characters. The name of the third column is price and its data type is double (double precision floating point number).
mysql> create table book (id integer, title varchar(40), price double); Query OK, 0 rows affected (0.13 sec)
Insert a new row into the book table. The order of the values correspond to the order of the columns within the create table command, so that the integer 1 is stored into the id column, the string XML Programming is stored into title column and the floating point number 34.0 into the price column.
mysql> insert into book values (1, 'XML Programming', 34.0); Query OK, 1 row affected (0.03 sec)
Display the data in all of the columns in all of the rows of the book table.
mysql> select * from book; +------+-----------------+-------+ | id | title | price | +------+-----------------+-------+ | 1 | XML Programming | 34 | | 2 | Algorithms | 42 | +------+-----------------+-------+ 2 rows in set (0.03 sec)
Drop the book table. This will delete all the data in the book table and remove its definition from the bookstore database.
mysql> drop table book; Query OK, 0 rows affected (0.08 sec)
Drop the bookstore database. This will delete the bookstore database and remove its definition from the database server.
mysql> drop database bookstore; Query OK, 0 rows affected (0.00 sec)
11.6.5 Examples
64
The first command given above creates an empty database called publisher. The second command creates a database user called publisher with password publisher (the argument of "identified by") and with privileges to perform all possible manipulations of the database. Inside Eclipse, create a folder in the publisher project called database and within that folder create a file called createdb.sql with the following contents. (If an external window pops up when you try this, then close this window and right click on cleandb.sql and select Open with text editor.)
create table news_item ( id integer primary key, title text not null, url text not null ); create table sequence ( next_value integer ); insert into sequence value (1000);
The first command in the above file is the SQL create table command. The command creates a table (in the currently selected database) called news_item with 3 fields. The first field is called id and it has datatype integer (an 8 byte signed integer) and it is declared as a primary key. A primary key is a field (or composite of several fields) that contains a unique value that can be used to identify the data in a single row in the table. The database enforces the uniqueness of this field, which means that if you try to insert a new row with a primary key equal to the primary key of an existing row, the insert operation will fail. The publisher application that we will subsequently discuss will follow the convention of making all primary keys integers (8-byte longs in Java) and they will all have the name id in which ever table they appear. The values for the primary keys will have no "business information." Such keys are refered to as surrogate primary keys or pseudo primary keys rather than natural primary keys, which do contain business information. After examining the publisher application, we will look at an application that implements a wiki. In the wiki 11.7 Create a Database of News Items 65
Java Web Programming with Eclipse application we will use natural primary keys. Each row in the the news_item table will contain information about a single news item in a news feed. The id field is used to uniquely identify the news_item. In addition to defining a primary key called id, the first command above also creates a field called title, which will contain the titles of news items, and a field called url, which will contain the link of the news article to which the news item refers. Both title and url are declared as text, which means they contain character data with a very large size limitation. These fields are also declared as not null, which means these fields must contain string data and can not be set to null. Note that setting a not null character field to an empty is allowed because this is different from setting the field to null. The second command in the above file is also a create table command. In this case, we create a table called sequence that will be used to store a single value: the next value to be used for a new primary key. The third command is an SQL insert command that inserts a row into the sequence table. By inserting the number 1000 in this table, we mean for our primary keys to begin from 1000. Every time we use a primary key, we will increment this value. Note that MySQL includes an auto_increment setting for integer primary keys and that many programmers use this as a way to automatically generate unique primary keys. It has the advantage of eliminating the need for a separate sequence table to store the next primary key value. However, this functionality is not part of the SQL standard and is not provided in all databases. For example, PostgreSQL does not provide an auto incrementing feature. For this reason, we use a separate sequence table, which is supported on all relational databases. The benefit is that we can replace the database with any other SQL compliant database without modifying our code. This type of portability is important when a software system may be used by multiple clients who prefer to use a database of their choise rather than the particular database the application is written for. Create another script called insertdb.sql with the following contents.
insert into news_item (id, title, url) values (1, 'CNN', 'http://www.cnn.com/'); insert into news_item (id, title, url) values (2, 'FOX News', 'http://www.foxnews.com/');
The purpose of insertdb.sql is to insert test data into the database. The above script insert two rows into the news_time table. As you can see from the syntax, the first part of the insert command specifies in a parenthetical list the name and order of the fields (or columns) to be set, and the second part of the command provides in a parenthetical list the values to be placed in those fields. Create another script called cleandb.sql with the following contents.
drop table if exists news_item; drop table if exists sequence;
The purpose of the cleandb.sql script is to delete all data in the database including the table definitions. As we develop the application incrementally, we will need to make frequent changes to the structure of the database. Each time we make a change to the structure of the database, we first run cleandb to delete everything, followed by createdb to create the new structure, followed by insertdb to insert new test data.
66
The root element of the build file is the project element. The project element has a required attribute called default, which defines a default target to execute. Under the root element there are various child elements, including target elements. The target elements represent the various jobs that you can execute. Each target element has a required attribute called name, which you can use to identify which targets you wish to run when you run ant. In our build file, the first child element under the root project element is a property element. Property elements such as this one simply assign a value to a name, which can be de-referenced elsewhere in the build file. In our build file, we assign the value -u publisher -ppublisher -D publisher to the name mysql.params. The value is a string that contains the command line parameters we need to pass to the mysql command line client when running the various scripts against the publisher database. Note that there is no space between -p and publisher. The first target all simply executes all the other targets, which is done by including the names of the other targets in the depends attribute of the all target. The second target cleandb runs the cleandb.sql script. The third target createdb runs the createdb.sql script. The fourth target insertdb runs the insertdb.sql script.
Java Web Programming with Eclipse 3. Check the createdb checkbox, and then check the insertdb checkbox in that order. 4. Look in the box titled Target Execution Order and verify that the order of execution is createdb, insertdb. The following screen shot shows the result of carrying out steps 1 through 4. 5. Select Run.
68
11.10 Exercises
11.10.1 (1) MAX function
Research the mysql documentation to find out how to obtain the largest value stored within a field in a table. Hint: use the MAX function within a select command.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 26, 2009 03:12 pm
11.10 Exercises
69
12.2 References
RSS Tutorial ROME JDOM
12.3 Overview
This chapter introduces the concept and basic technique of generating Web pages from a database. We illustrate this process by converting the publisher application from a static news feed to a dynamic news feed. Actually, what we generate is not exactly a web page; rather, it is an XML document containing news feed data. In later chapters, we use the same procedures described here to generate HTML documents, which form the basis of web pages. Recall that the publisher application returns a static RSS document to client applications. In this chapter we replace the static RSS document with a servlet that dynamically generates the RSS news feed from the publisher database created in the MySQL chapter. We do this by directly submitting an SQL select statement to the database from within the NewsFeedServlet that we create. The following diagram illustrates this architecture. Later, we will use a diffirent architecture: one that isolates database interaction away from the servlets.
Java Web Programming with Eclipse The reason we place the database driver in the lib folder of Tomcat instead of the usual location in WEB-INF/lib is that we will configure Tomcat to create and manage a pool of database connections that all web applications installed with Tomcat will access. For this to work, we need to place the MySQL JDBC driver library in the runtime classpath of Tomcat. The reason we do not add the MySQL Connector/J jar file to the project's build path is that we do not access any classes or interfaces in this library at build time: only at runetime. Our applictoin only accesses components of the JDBC API that are part of the core Java library. The MySQL Connector/J jar file contains implementations of the service provider's interface of JDBC, which is hidden from our application and needed only at runtime. Using database connection pools is standard practice because it eliminates costly re-establishment of dropped database connections. Because web applications need to process frequent page requests from multiple clients, the application needs to make frequent connections to the database. Thus, database pooling makes sense in this environment.
The project also needs a reference to external jar file servlet-api.jar. If this is not already in your project build path, then you should add it to the build path. To do this, right click on the project folder and select Properties. Select Java Build Path and then select the Libraries tab. Click on the Add External Libraries button and navigate to ${TOMCAT_HOME}/lib and then select servlet-api.jar. The reason we do not add servlet-api.jar to the projects lib folder is that servlet-api.jar is already present in the runtime class path by virtue of being in the Tomcat lib folder. So, we only need to add it to the project's build path.
71
Java Web Programming with Eclipse Start by creating a new class called NewsFeedServlet that extends HttpServlet and is located in the package publisher.web. See the procedure described for creating the HomeServlet in the Java Servlet chapter. We are going to write logging messages in this servlet. For this purpose, we declare the following member variable.
private Logger logger = Logger.getLogger(this.getClass());
The init method of a servlet is invoked by the servlet container prior to using the servlet for the first time. The init method is therefore used to perform initialization for a servlet. In our case, we need to have the mysql JDBC driver register itself with the JDBC system, so that the JDBC system uses its classes to communicate with the mysql database server. In the following, we do this in the init method of the NewsFeedServlet. In NewsFeedServlet, override the init(ServletConfig) method that it inherits. (The procedure for overriding inherited methods efficiently in Eclipse is described in the chapter on servlets; see the section in which you create a home servlet.) Use the following code for the implementation of init to allow the MySQL JDBC driver to register itself with the JDBC system.
public void init(ServletConfig config) throws ServletException { logger.debug("init()"); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new ServletException(e); } }
The method Class.forName in the above code takes the name of a class and returns an instance of Class for it. In our case, this causes the class com.mysql.jdbc.Driver to be loaded, which causes its static initialization code to run. This initialization code registers the class with the JDBC system. Note that the byte code that defines com.mysql.jdbc.Driver is located in the MySQL Connector/J jar file, which we added to the web application's runtime classpath by placing it within WEB-INF/lib. The following code shows how to connect to the database, generate a news feed XML document from it, and return the document to the client. Add the following code to the news feed servlet.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { SyndFeed feed = new SyndFeedImpl(); feed.setFeedType("rss_2.0"); feed.setTitle("My Local News Feed"); feed.setLink("http://localhost:8080/publisher/"); feed.setDescription("This feed was created using ROME."); List<SyndEntry> entries = new ArrayList<SyndEntry>(); try { Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost/publisher", "publisher", "publisher"); Statement statement = connection.createStatement(); ResultSet resultSet = statement .executeQuery("select * from news_item;"); while (resultSet.next()) { String title = resultSet.getString("title"); String url = resultSet.getString("url");
72
When you organize imports, select the following classes from the alternative presented. java.sql.Statement org.apache.log4j.Logger java.sql.Connection java.util.List The NewsFeedServlet uses JDBC classes (from packages java.sql and javax.sql) to retrieve the news items from the database. It uses ROME classes (from package com.sun.syndication.feed.synd) to construct the RSS document in memory and it uses the SyndFeedOutput class (from package com.sun.syndication.feed.synd) to write the document into the output stream provided by the response object. In the doGet method of the news feed servlet, we start by constructing a instance of SyndFeed. This object represents the XML document that we return to clients. We set the feed type, title, link and description for the overall news feed. We then use a while loop to construct the individual entries that comripse the news feed. Prior to entering the while loop, we issue an SQL select command to retrieve from the database all of the news item data. Recall that a select command results in a table of rows and columns. In Java, this tabular result of a select command is represented as an instance of the ResultSet class. It is returned by the executeQuery method of a Statement object. The ResultSet contains an internal row pointer, which is initially set to one before the first row. We call the next method of the ResultSet to advance the pointer to the next row. If a next row exists, next returns true, otherwise, next returns false. Thus, we use the value returned by next as the loop condition. For each row in the ResultSet, we construct a news feed entry, and add this to the SyndFeed object that we created prior to entering the loop. The following shows the XML fragment that we build in this loop.
<rss> <channel> <title></title> <item> <title></title>
73
Finally, we use the SyndFeedOutput class from the ROME library and the OutputStream from the HttpServletResponse object to send the RSS document to the client (the website application in our example). Note that we need to specify the content-type of the object we return to the client, which we do by invoking the setContentType method of the response object with the string text/xml. We don't need to specify a content-type when generating html from JSPs because the JSPs will automatically set the content-type to text/html. Modify the web.xml file, so that requests matching /news.rss are sent to NewsFeedServlet. To do this, insert the contents of the following listing into the web.xml file. 12.6.1 web.xml
<?xml version="1.0"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4 version="2.4"> <servlet> <servlet-name>news-feed</servlet-name> <servlet-class>publisher.web.NewsFeedServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>news-feed</servlet-name> <url-pattern>/news.rss</url-pattern> </servlet-mapping> </web-app>
12.7 Test
Restart the publisher application and verify that the news feed servlet of the publisher application is working correctly by going to http://localhost:8080/publisher/news.rss. You should be able to view the XML document that the servlet generates. After verifying that the news feed servlet is working correctly, go to http://localhost:8080/website/home and verify that the home servlet is retrieving your news feed and processes it correctly. The result is shown in the following screen shot.
12.6.1 web.xml
74
12.8 Exercises
12.8.1 (1) Add news
Add the following news item to the news_item table in the publisher database and verify that the change appears in the home page of the website application.
insert into news_item (id, title, url) values (3, 'ABC News', 'http://www.abcnews.com/');
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 24, 2009 12:46 pm
75
76
13.2 References
Tomcat home page DataSource interface
13.3 Overview
In this chapter, we modify our approach to getting database connection objects. Rather than getting the connection object through the DriverManager class, we get them through an instance of the DataSource class. This is considered a best practice because a DataSource object maintains a pool of persistent database connections in order to eliminate the time consuming step of establishing a database connection each time the application wishes to interact with the database.
13.4.1 publisher.xml
<Context path="/publisher" docBase="${WORKSPACE}/publisher/web"> <Resource name="datasource" type="javax.sql.DataSource" auth="Container" maxActive="10" maxIdle="3" maxWait="10000" username="publisher" password="publisher" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/publisher?autoReconnect=true" /> </Context>
77
Java Web Programming with Eclipse To make the above change effective, you need to re-deploy the publisher application. To do this, go to the Tomcat Manager application, undeploy the publisher application, and then deploy the publisher application. After doing this, it is a good idea to check the log files to make sure that deployment was successful. If deployment failed, you need to fix the problem before continuing.
Organize imports on the above addition to the news feed servlet and select the following class. javax.sql.DataSource We will follow a pattern called dependency injection to set the data source variable. In dependency injection, resources needed by components, such as the data source in our example, are set by initialization code external to the component. The alternative to dependency injection is for the component to acquire its own resources. For this to work in our case, we need to provide a means for external code to set the data source in the news feed servlet. The following code does this.
public static void setDataSource(DataSource dataSource) { NewsFeedServlet.dataSource = dataSource; }
We make the data source a static property for 2 reasons. First, to remain general, we want allow multiple instances of servlets to be created in our applications (even though typically only a single instance is created), having multiple data source instances passed into these multiple instances defeats the purpose of pooling. Second, the servlets that depend on the data source may not have been created when our initialization code runs. By using a static property, we eliminate the need of doing additional work to assure that all these servlet instances are first created. The following code currently appears in our news feed servlet.
Connection connection = DriverManager.getConnection( "jdbc:mysql://127.0.0.1/publisher", "publisher", "publisher");
The above code should be replaced with the following in order to obtain database connections from the connection pool.
Connection connection = dataSource.getConnection();
When using database connection pooling, it is important to close connections and their associated objects when finished with them. If this is not done, the pool of available connections inside the DataSource will become exhausted and application threads will block and wait indefinitely for an available connection.
13.4.1 publisher.xml
78
import org.apache.log4j.Logger; public class Init implements ServletContextListener { private Logger logger = Logger.getLogger(this.getClass()); public void contextDestroyed(ServletContextEvent sce) { } private void contextInitialized2(ServletContext servletContext) throws Exception { InitialContext enc = new InitialContext(); Context compContext = (Context) enc.lookup("java:comp/env"); DataSource dataSource = (DataSource) compContext.lookup("datasource"); NewsFeedServlet.setDataSource(dataSource); } public void contextInitialized(ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext(); try { contextInitialized2(servletContext); } catch (Exception e) { logger.error("Initialization failed.", e); throw new RuntimeException(e); } logger.debug("Initialization succeeded."); } }
We have already configured the web container to create a data source for the publisher web application. In order to access this data source, we use the Java Naming and Directory Interface (JNDI) to obtain a reference to the DataSource object created by the container. In the contextInitialized2 method shown above, the first thing we do is create an instance of InitialContext. This is the starting point to locate resources provided through JNDI. In the next line, we narrow the context by calling the lookup method with the name java:comp/env. We named the resulting context enc because it represents the environment naming context (ENC). We then perform a lookup through the ENC on the name datasource to obtain a reference to the data source.
79
Java Web Programming with Eclipse In order for Tomcat to call the contextInitialized method of your Init class, we need to add a listener element to the application's deployment descriptor. Add the following listener element as a child to the web-app element in the deployment descriptor web.xml.
<listener> <listener-class>publisher.web.Init</listener-class> </listener>
Later, we will use the Init class to perform other initializations for the web application. Depending on your version of Tomcat, you may also need to add the following to the deployment descriptor. This is not needed for Tomcat version 6.
<resource-ref> <description>dataSource</description> <res-ref-name>datasource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
13.7 Test
Make the publisher application reload its deployment descriptor by stoping and starting it through the manager application. Then go to http://localhost:8080/website/home to verify that the website application can still obtain the news feed from the publisher application.
13.8 Exercises
13.8.1 (1) Anticipating problems
Introduce the following errors into the code and describe the effects. Omit the listener element from the deployment descriptor. Inside Init, replace compContext.lookup("datasource"); with compContext.lookup("badsource"); Inside Init, fail to set the data source in the news feed servlet. Introduce an additional error of your choosing and describe the effects.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 05, 2009 04:09 pm
13.7 Test
80
14.2 References
Data Access Object
14.3 Overview
In the previous chapter we showed how to access the database directly from servlet code. This architecture is illustrated in the following diagram.
The problem with this approach is that code to interact with the database tends to grow and becomes mixed with logic that directly deals with solving the problem at hand. Also, the code that is used is similar from one instance to the next, giving rise to code duplication. To solve these problems, we improve the architecture by defining persistent classes with their corresponding data access objects (DAOs). This allows us to express application logic in terms of manipulation of business objects such as NewsItem and User rather than operating on separate data fields taken from columns in the database. The following diagram illustrates the revised arhitecture.
Normally, code devoted to managing the persistent state of objects comprises a large percentage of the total code. Because this type of code can be generalized, libraries have been developed that provide developers with a framework to implement object persistence in their applications. These frameworks are referred to as object-relational mapping (ORM) frameworks because they provide the means to move data represented as 14 Data Access Objects 81
Java Web Programming with Eclipse objects in code into, and out of, relational databases. Two well-known open source ORM frameworks include Hibernate and iBatis. Use of an ORM persistence framework is outside the scope of this book. In this book, we look at a simple approach to implementing object persistence. However, as a real application would grow, our simple approach would become more complex, so that adoption of an ORM framework would be more cost-effective in the long run. In this section, you will define a class called NewsItem that represents individual news items that are stored in the database. The news item class is considered to be persistent because the news item data in the database continues to exist between restarts of the web application. It is also referred to as a business object, or domain object, because it corresponds directly to an entity in the problem space. You will also define the class NewsItemDAO to provide a means to manage the persistent instances of the news item class. In general, data access object classes (DAOs) hide database-specific activities from the system and present an object-oriented interface to manage persistent data. When thinking about DAOs, you should remember that each DAO is responsible for managing instances of a single class. For this reason, we append the initials DAO with the name of the class being managed. Thus, the class NewsItemDAO manages instances of class NewsItem. In our architecture, persistent instances of a class are identified through a member variable called id, which corresponds to a primary key in the database. Therefore, to retrieve a specific instance of a class, you would typically provide the object's id to a find() method of the object's DAO. Standard methods provided by a DAO include the following, where Object is replaced by whatever class the DAO manages.
Object find(Long id); List findAll(); void update(Object object); void create(Object object); void delete(Object object); // // // // // returns null if object doesn't exist always returns a collection, but may be empty throws NotFoundException if object doesn't exist sets the object's id as a side effect silently ignores already deleted objects
In addition to the above standard methods, additional methods may be needed to support the particular needs of an application. Typically, these will be variations of the find and findAll methods. The following are some examples.
User findByUsername(String username); List findAllExpired(); List findAllExpiredByType(Type type);
Use the following procedure to generate the getter and setter methods for these variables.
82
Java Web Programming with Eclipse 1. Selecting Source - Generate Getters and Setters. 2. Click the Select All button. 3. Click the OK button.
14.5.1 DataAccessObject.java
package publisher.data; import import import import import java.sql.Connection; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; java.sql.Statement;
import javax.sql.DataSource; public class DataAccessObject { private static DataSource dataSource; private static Object idLock = new Object(); public static void setDataSource(DataSource dataSource) { DataAccessObject.dataSource = dataSource; } protected static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } } protected static void close(Statement statement, Connection connection) { close(null, statement, connection); } protected static void close(ResultSet rs, Statement statement, Connection connection) { try { if (rs != null) rs.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (SQLException e) { throw new RuntimeException(e);
83
The data access object class given above contains two member variables: id and idLock. We can place the variable id in this parent class because we will consistently follow the pattern of using an id in every persistent class that we create. Recall that this id is the surrogate primary key used in the database table that stores instances of the persistent class. The idLock variable is declared as static, which means that a single instance of idLock is available at all times and is shared by all instances of the data access object class and its subclass instances. The idLock variable is used to lock the sequence table in the database so that only a single thread may access the table at one time. If you look inside the getUniqueId method, you can see that idLock is used as an argument to a synchronized statement. The synchronized statement allows only a single thread to enter the code block it contains. Condenting threads are keep waiting and allowed to enter and exit one at a time. To understand why this is necessary, suppose for a moment that we omit the synchronization and let threads execute statements in getUniqueId without regard to the presence of other threads. Suppose that thread A executes the query to get the value of next_value, which is 1000. However, before it gets to write the next value 1001 into the database thread A goes to sleep and thread B enters getUniqueId. Thread B also reads next_value from the database, which is still 1000. Thread B then updates next_value in the database to 1001. When B sleeps and A wakes up, A will redundently update next_value to 1001 in the database. So far, there is no runtime error, however A and B are in the process of creating separate news item instances with the same id, which they intend to use as primary key values for 2 different rows in the the news item table. The first thread that inserts its data into the database will succeed, but the second thread that attempts an insert will fail 14.5.1 DataAccessObject.java 84
Java Web Programming with Eclipse because it will violate the primary key constraint of uniqueness by using a value for id that already exists in the table. This is a runtime error that will generate an exception. Our solution for generating unique primary key values will only work in systems that are deployed as single instances. If multple instances of the systems are deployed in order to handle levels of traffic that a single instance can not handle, then the idLock variable will not be shared between instances, which could result in generation of non-unique keys. In this situation, you need to use a different mechanism. This book does not cover these alternatives. After creating the data access object class, you need to add the following statement to the contextInitialized method of the Init class, so that a data source reference can be passed into the data access object class when the application initializes. Make sure that this statement follows the line that sets the dataSource variable.
DataAccessObject.setDataSource(dataSource);
You need to organize imports in order to generate an import for the DataAccessObject class. While your at it, you should also remove the following line from Init, since direct access to the data source is being removed from servlets and being kept wholely within the data access objects.
NewsFeedServlet.setDataSource(dataSource);
Organize imports, and select the following class among the alternatives.
85
Java Web Programming with Eclipse java.sql.PreparedStatement java.sql.Connection The code does not yet compile because the read method is not yet defined. We will define this later. The find method given above takes a long id as an argument and returns an instance of NewsItem. This method will execute the following SQL select command to locate the row within the news_item table that contains the id passed into the find method.
select * from news_item where id=?
The question mark in the above SQL statement is replaced by the value of the id passed into find by the following command.
statement.setLong(1, id.longValue());
The first argument in the setLong method given above is an integer n that refers to the nth question mark in the SQL statement that was used to create the prepared statement (not including question marks that may occur inside data values). (Note that numbering of question marks starts at 1 and not 0.) We pass in the value of the id so that the where clause attached to the select statement is narrowed to only those rows with id field equal to the one we specify. Because id is a primary key, it contains a unque value, so the table resulting from the select command will have either zero rows or one row. If the resulting table (returned as a ResultSet) contains zero rows, it means that a news item with id equal to the given id does not exist. In this case, the find method returns null. If the resulting table contains one row, then the news item with the given id exists. We therefore create an instance of the news item class and set its attributes according to the values found in the returned row. This job is handled by a separate read method. The reason we place the operations into a separate method is that we will need to carry out the same operations for other methods in the news item DAO. By placing these common operations in their own read method, we reduce code duplication. Minimizing code duplication is important because it makes the program easier to manage, since changes to common functionality only need to by made in one place. The following listing provides the implementation of the read method, which you should add to the news item DAO class.
private NewsItem read(ResultSet rs) throws SQLException { Long id = new Long(rs.getLong("id")); String title = rs.getString("title"); String url = rs.getString("url"); NewsItem newsItem = new NewsItem(); newsItem.setId(id); newsItem.setTitle(title); newsItem.setUrl(url); return newsItem; }
We declare the read method as private because only methods within the news item DAO will call read. If we give the method greater visibility by declaring it public, the code will still function as needed; however, we would be violating a widely accepted best practice of limiting visibility as much as possible. The benefit of following this practice is that it improves readability of the code. If we make the read method private, the reader of the code knows that only internal methods will call the read method. If we declared it as public, the 14.6 Create NewsItemDAO 86
Java Web Programming with Eclipse reader of the code may be misled into thinking that code outside the class is calling into the read method. The above find method will be used in the next chapter by various servlets to extract a single news item from the database. However, the news feed servlet that we are developing in this chapter needs to extract all news items from the database. For this purpose, add the following implementation of the findAll method to the news item DAO.
public List<NewsItem> findAll() { LinkedList<NewsItem> newsItems = new LinkedList<NewsItem>(); ResultSet rs = null; PreparedStatement statement = null; Connection connection = null; try { connection = getConnection(); String sql = "select * from news_item order by id"; statement = connection.prepareStatement(sql); rs = statement.executeQuery(); while (rs.next()) { NewsItem newsItem = read(rs); newsItems.add(newsItem); } return newsItems; } catch (SQLException e) { throw new RuntimeException(e); } finally { close(rs, statement, connection); } }
Organize imports, and select the following class among the alternatives. java.util.List The findAll method selects all the rows and columns of the news_item table and then populates a linked list with instances of the news item class and return this to the caller. If no news items a found, we return a linked list that is empty. Notice that for every row in the result set, we call the read method to extract column values and place them in a news item instance.
87
Organize imports and select the following classes from the alternatives. java.util.Iterator
14.8 Test
Reload the publisher application and verify that the application can still obtain the news feed from the publisher application by going to http://localhost:8080/website/home.
14.9 Exercises
14.9.1 (1) PubDate field
If you have not carried over the publication date field from your solution to the PubDate exercise in the database-driven web applications chapter, then incorporate it back into the publisher and website web applications.
Modify the website application so that it displays a descritpion for each new item.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 13, 2009 05:27 pm
14.8 Test
88
15 Item Management
15.1 Objectives
Understand how to implement item management Learn about use case diagrams, page flow diagrams and sequence diagrams Learn how to develop a page layout mechanism in JSP Understand what is meant by a layered architecture Learn how to process form submissions
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 13, 2009 07:42 pm
15 Item Management
89
In a larger application, it is not usually necessary to enumerate the detailed use cases shown in the above figure. Instead, these use cases are compressed into a single use case called something like manage items as illustrated in the following figure.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. 16 Item Management (continued) 90
Java Web Programming with Eclipse Java Web Programming with Eclipse contents Last modified February 13, 2009 07:46 pm
91
The page flow diagram above illustrates the connections between a subset of pages in the application. Not shown in the diagram is the publisher application home page. From the home page, the user will be able to go to the list items page or the create item page. These two transitions will be made possible through a global menu (appearing on every page) that provides the following choices. List news items Create news item Logout The logout operation available in the global menu will be dicsussed in a later chapter.
92
Java Web Programming with Eclipse The purpose of the create item page is to allow users to input data for the creation of new items. This page will therefore contain a form with fields empty or set to default values. A user chooses to either save the newly specified item or cancel the creation operation. When a user chooses to save the new item, the data being submitted is subjected to a validation test. A validation test decides if the data being submitted violates any constraints placed on the data. For example, in our application, the title field and the link fields cannot be empty. If a user submits an empty value for either of these fields, the submission will fail the validation test. If the submission fails validation, the user is kept on the item creation page, but the system adds notation to inform the user of the problems. If the data passes validation, the user is presented with the view item page. The purpose of sending the user to the view page is that it allows the user to see that the new item has been created in the system. The alternative to going to the view item page is to go to the list items page, because the user can also see on this page that the new item has been created, becuase it now appears in the list. However, if the list is long, the user must expend mental effort to search the list and locate the new item. However, only a summary of the new item appears in the list items page,\ so that user may suffer some doubt that all the details he or she specified entered into the system correctly. The user would need to go to the view item page in order to verify this. The list items page lists all the items in the system. This can be developed, of course, so that the user can specify a filter in order to generate smaller lists that contain only items that satisfy the criteria in the filter. For example, the user might be given the choice of listing only news feed entries that fall within a given category of news. From list items page, the user can navigate to an individual news item, which is displayed in the view item page. The view item page presents the detailed information associated with an individual item. The particular item that is being viewed on the page is considered the current item that is subject to the two available operations of delete and edit. The delete item page is a confirmation page that is arrived at when the user selects to delete the current item shown in the view item page. It's important to provide a confirm step, because the user may have mistakenly selected the delete operation from the view item page. If the user confirms the delete, the item is deleted from the system and the user is sent to the list items page. The user can see that the item has been deleted because it no longer appears with the list items page. If the user cancels the delete operation, the user is sent back to the view page from where he or she came. Bringing the user back to the view page allows the user to verify that the delete operation was canceled. It's important to use unambiguous and simple language in all the pages, but especially in the delete page. Consider the following two alternatives for the wording on the delete page.
Are you sure you wish to delete this item? Are you sure you wish to delete this item? yes delete no cancel
The second wording is preferable to the first because the two answers can almost stand independently of the question. From the question, the user understands that the delete operation is being postponed until he or she confirms at this point. The yes/no answers require the user to refer back to the question to make sure that the answer given is correct, whereas the delete/cancel answers can be understood in relation to the simpler notion that the system is asking the user to confirm the delete operation. The edit page allows the user to change data associated with the item. This page is the same as the create item page except for two differences. First, the edit item page presents a form with all fields set to the current values of the item, rather than being blank or set to default values. Second, when the user cancels from the edit page, the user is taken back to the view item page rather than the list items page. 17.1.1 Page Flow Diagram 93
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 13, 2009 07:42 pm
94
The areas that are filled with green are considered dynamic page content. The banner and static menu are generated from top.inc and the footer is generated from bottom.inc.
95
<table width="728" cellspacing="0" cellpadding="0" style="padding: 0; margin: 0; border-collapse: collapse"> <tr style="padding: 0; margin: 0"> <td width="728" colspan="2" style="padding: 0; margin: 0"><img src="logo.gif" style="padding: 0; margin"></td> </tr> <tr style="padding: 0; margin: 0"> <td width="728" colspan="2" style="padding: 0; margin: 0"><div style="padding: 0; margin: 0; text-align: center; font-size: small; background-color: #99CCCC"> Publisher Application </div></td> </tr> <tr> <td rowspan="2" width="240" valign="top"> <div style="height: 500px; padding: 20px; border-right: 3px dashed; margin-right: 20px"> <a href="list-news-items">List News Items</a><br/> <a href="create-news-item">Create News Item</a><br/> <a href="logout">Logout</a> <br/> </div> </td> <td width="488"> <div style="margin-top: 12px; margin-bottom: 12 px"> <!-- start of page-specific menu --> <a href="edit?item=3">edit</a> <a href="delete?item=3">delete</a> <!-- end of page-specific menu --> </div> </td> </tr> <tr> <td valign="top"> <!-- start of page content --> <h1 style="font-size: larger">View News Item</h1> <p>Title: California State University San Bernardino</p> <p>Link: <a href="http://csusb.edu/">http://csusb.edu/</a></p> <!-- end of page content --> </td> </tr> </table> </body> </html>
96
Java Web Programming with Eclipse There are 4 HTML comments in the above listing that delimit the two areas that will change between web pages. All other areas in the above example can be identical between web pages. If we keep the static content in a single location, it will be much easier to make global changes to the design of our pages. One way to do this is to carve the example HTML into three separate pieces and store them in files to be included by the JSP files that need them. The structure of our JSP files will then be as follows.
<%@ include <!-- page <%@ include <!-- page <%@ include file="top.inc" %> menu --> file="middle.inc" %> content --> file="bottom.inc" %>
You should create these 3 files now, placing them in web/WEB-INF/jsp. When you are done, the 3 files should look like the following.
18.1.3 top.inc
<html> <head> <title>Publisher Application</title> </head> <body style="margin: 0; padding: 0">
<table width="728" cellspacing="0" cellpadding="0" style="padding: 0; margin: 0; border-collapse: collapse"> <tr style="padding: 0; margin: 0"> <td width="728" colspan="2" style="padding: 0; margin: 0"><img src="logo.gif" style="padding: 0; margin"></td> </tr> <tr style="padding: 0; margin: 0"> <td width="728" colspan="2" style="padding: 0; margin: 0"><div style="padding: 0; margin: 0; text-align: center; font-size: small; background-color: #99CCCC"> Publisher Application </div></td> </tr> <tr> <td rowspan="2" width="240" valign="top"> <div style="height: 500px; padding: 20px; border-right: 3px dashed; margin-right: 20px"> <a href="list-news-items">List News Items</a><br/> <a href="create-news-item">Create News Item</a><br/> <a href="logout">Logout</a> <br/> </div> </td>
18.1.3 top.inc
97
18.1.4 middle.inc
</div> </td> </tr> <tr> <td valign="top">
18.1.5 bottom.inc
</td> </tr> </table> </body> </html>
The banner in the the publisher application web pages comes from an image file called logo.gif. You should store this directly within the web folder of the publisher project.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 25, 2009 07:42 pm
18.1.4 middle.inc
98
The following screen shot shows the various concerns within our application organized into a layered architecture. This architecture will form a basis for future iterations of the system in which we add functionality.
Actually, the architecture is not purely layered in the sense that elements of the presentation layer access elements of the persistence layer. In a strictly layered architecture, elements of the presentation layer would only be permitted to access elements of the business logic layer. In the outermost layer, there is the user's web browser that makes TCP connections to the tomcat web container (also called a servlet/JSP container), through which it sends HTTP request messages.
99
Java Web Programming with Eclipse The second layer is Tomcat, which parses incoming HTTP request messages into instances of the HttpSerlvetRequest class, and then passes these objects to the doGet or doPost methods of an appropriate servlet based on the request URL. The third layer is the presentation layer, which is comprised of servlets and JSP scripts. The servlets act as controllers (request handlers) because their service methods (doGet, doPost) act as entry points into the web application. In response to user input, the servlets may lookup one or more business objects through the persistence layer and may invoke requested business functionality on them. After business functions have completed, the servlets invoke JSP scripts, passing to them references to appropriate domain objects. The purpose of the JSP is to generate the HTML to display to the user an appropriate view of the application state. Some authors talk about a model-view-controller architecture in which servlets comprise the controller, JSP the view, and business logic the model. The domain objects are plain old Java objects (POJOs) that model the data and behaviors of the (business) problem being solved. In our simple application, the business logic layer is comprised of instances of a class called NewsItem. The persistence service is comprised of data access objects (DAOs). Recall that these classes are responsible for providing services needed to persist the application state as embodied in the domain objects. For each persistent domain object, there is a DAO; thus for our application, we have a single class called NewsItemDAO. Finally, the database is situated on the lowest layer of the application. Reads and writes into the database will be performed by the methods in the DAOs. The following screen shot provides another illustration of the basic architecture that will be followed in this chapter.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 10, 2009 03:12 pm
100
import org.apache.log4j.Logger; public class HomeServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); private RequestDispatcher jsp; public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); jsp = context.getRequestDispatcher("/WEB-INF/jsp/home.jsp");
101
Now, we are ready to create the jsp file that the home servlet will forward to in order to generate the HTML. Create a file home.jsp inside the jsp folder with the contents of the following listing.
<%@ include file="top.inc" %> <%@ include file="middle.inc" %> <h1>Welcome</h1> <p> This is the publisher application. It allows you to publish and manage a news feed. </p> <%@ include file="bottom.inc" %>
Because the home page has no page specific operations for the user, the section between the top and bottom includes is empty.
20.1.4 Test
Have Tomcat reprocess the web.xml file by stoping and starting the publisher application through the manager application and verify that the application is running correctly by going to the home page of the publisher application. The following screen shot shows approximately how the home page is rendered.
102
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 10, 2009 03:51 pm
20.1.4 Test
103
import org.apache.log4j.Logger; import publisher.data.NewsItem; import publisher.data.NewsItemDAO; public class ListNewsItemsServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); private RequestDispatcher jsp; public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); jsp = context.getRequestDispatcher("/WEB-INF/jsp/list-news-items.jsp"); }
104
21.1.5 Test
Stop and start the publisher application with the Tomcat manager application, so that Tomcat reloads the web.xml file and the new servlet. Verify that the the new functionality works correctly by going to http://localhost:8080/publisher/home and following the link to the list items page. The following figure shows approximately how the list news items page should render.
105
Note that the links on the list items page will not work yet. In the next section we implement the view item page, so that the links to the news items in the list will bring the user to the view item page.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 16, 2009 07:23 pm
21.1.5 Test
106
import org.apache.log4j.Logger; import publisher.data.NewsItem; import publisher.data.NewsItemDAO; public class ViewNewsItemServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); private RequestDispatcher jsp;
107
22.1.5 Test
Stop and start the publisher application with the Tomcat manager application, so that Tomcat reloads the web.xml file and the new servlet. Verify that the new functionality works correctly by going to http://localhost:8080/publisher/home and following the link to the list items page and then clicking on a title to go to the view item page for that news item. The following figure shows approximately how the view news item page should render.
108
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 25, 2009 07:47 pm
22.1.5 Test
109
110
When the user wishes to modify a news item, he or she first views the object through the view-news-item page. In this page, there is an edit link. When the user clicks the edit link, the browser will send an HTTP GET request for the following resource (assuming the selected NewsItem has an id equal to 3):
/edit-news-item?id=3
The doGet method of EditNewsItemServlet extracts the value of the id parameter, which is 3 in our example, and then passes this value to the find method of the news item DAO. The servlet then stores a reference to the news item instance returned by the find method in the HttpServletRequest object (which acts as a container for request-specific data), and then invokes the forward method on an instance of the RequestDispathcer class that encapsulates the JSP that generates the HTML for the edit form. The edit-news-item JSP uses the properties of the news item instance to populate its form fields, so the user can modify the current state of the selected news item. The following figure is a sequence diagram that illustrates the sequence of activities that result when the user submits changes to the news item edit form, which is the second step in the two-step business transaction.
23.1.1 Overview
111
After the user finishes making edits to the news item, the user clicks the submit button to save the changes. When this happens, the browser constructs an HTTP POST request message with the data from the form and sends it to the servlet container. The servlet container parses the request message into an instance of the HttpServletRequest class and passes this to the doPost method of the singleton instance of the EditNewsItemServlet class. The servlet container also passes an instance of HttpServletResponse, which is used to construct a response to be sent back to the browser. The doPost method of the EditNewsItemServlet instance checks to see if the data entered by the user is valid (a process called validation), and if valid, invokes the update method of the news item DAO to modify the attributes of the given news item according to the values entered by the user in the HTML form. After updating the database, the servlet redirects the browser to the view-news-item page, which causes the browser to submit a separate HTTP request to the web application to view the result of the edit operation.
112
As you can see, the update method issues an SQL update command to modify the state of a news item in the news item table. Note that it is possible that another user deleted the news item just prior to executing the update method. When this happens, the call to execute will throw an SQLException. We wrap the SQLException in a RuntimeException so that we can throw it to calling code with declaring the method with a throws clause. We can do this because RuntimeException is an unchecked exception. Throwing unchecked exceptions simplifies the code by avoid the need to explicitly throw or catch exceptions. Using unchecked exceptions is the current trend in programming style; all exception in C# for instance are unchecked. The finally clause ensures that we call the close method regardless of whether an exception occurs. Remeber that closing database connections is essential when using database connection pooling. If we fail to close connection, we will exhaust the connection pool and threads will start blocking forever on calls for new connections.
113
114
There are two ways the doPost methods will be called: the user clicks cancel or the user clicks submit. Accordingly, the doPost method first checks to see if the user clicked on cancel. If the user clicked cancel, then the doPost method will redirect the browser back to the view-news-item page. If the user clicked submit, then doPost will check to see that the data entered by the user is valid, which it does by calling the validate method. The validate method is implemented as a static method because it will also be called from the doPost method of the servlet that will be used to handle requests to create news items. By placing the code in its own method that can be externally invoked, we keep the validation code in a single location and avoid creating duplicate code. The validate method returns a map that contains an entry for each validation error that is detected. Therefore, the doPost method checks to see if any validation errors occurred by checking to see if this map is empty. If the map is not empty, then it forwards processing of the request to the jsp with the edit form, which will display the data entered by the user in the form along with the error messages. If there are no entries in the errors map, then doPost will consider the data submission to be valid and will then proceed to store the new values in the database. The validate method extracts the title and url attributes from the request parameters. It checks to see if the values submitted by the user are valid. If a submitted value is invalid, the validate method adds an entry in a map called errors. The errors map associates a parameter in the form with a validation error message, and it is returned by the validate method. In addition to checking for validation errors, the validate method has a side effect: it stores the values of the parameters as attributes in the request object. The reason for doing this is that if there are validation errors, then the calling code will forward the request to the jsp with the form; the jsp needs access to the values the user submitted in order to echo them back to the user.
115
Notice how field-specific error messages are displayed next to their fields.
23.3.3 Test
Stop and start the publisher application with the Tomcat manager application, so that Tomcat reloads the web.xml file and the new class files. Verify that the new functionality works correctly by going to http://localhost:8080/publisher/home and editing an existing news item. You should try entering in an empty title and an empty url to see how validation works. The following figure shows approximately how the edit news item page should render.
116
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 25, 2009 07:52 pm
23.3.3 Test
117
The create method takes an instance of the NewsItem class and inserts a row in the news_item table to represent this instance. The create method generates a unique id to serve as a primary key for the newly inserted news item. It sets the id field of the NewsItem object passed into it, so that the calling code has access to this newly generated value. It is possible to have MySQL generate a unique id as part of the insert command. This is done by declaring the id column with auto_increment during table creation. However, this feature is not part of standard SQL and is not implemented in all relational database servers. To keep the code portable to these other servers, we choose to generate our own primary keys.
118
import org.apache.log4j.Logger; import publisher.data.NewsItem; import publisher.data.NewsItemDAO; public class CreateNewsItemServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); private RequestDispatcher jsp; public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); jsp = context.getRequestDispatcher("/WEB-INF/jsp/edit-news-item.jsp"); }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletExcepti { logger.debug("doGet()"); jsp.forward(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Check if cancel button was pressed. String cancelButton = req.getParameter("cancel-button"); if (cancelButton != null) { logger.debug("cancel button pressed"); resp.sendRedirect("list-news-items"); return; } Map<String, String> errors = EditNewsItemServlet.validate(req); if (!errors.isEmpty()) { logger.debug("validation errors"); jsp.forward(req, resp);
119
In the doPost method, the first thing we do is check for the cancel button. If pressed, we send the user to the list-news-items page. If the cancel button was not pressed, we validate and bind form data to an instance of NewsItem. If there are validation errors, we pass the newsItem and errors objects to the jsp to display the user input and the validation error messages. Validation and binding for object creation and object editing are identical. For this reason, we invoke validate in EditNewsItemServlet, rather than replicate the code in CreateNewsItem. For this to work, we declared the validateAndBind method of EditNewsItemServlet as static. If there are no validation errors, we invoke the create method of the NewsItemDAO class. Unlike EditNewsItemServlet, we don't need to worry about NotFoundException. After creating the news item in the database, we return the user to the view-news-item page, so that he can verify that the news item was created. (Alternatively, we could have redirected the user to the list-news-items page.) The create method of NewsItemDAO has the side effect of setting the id attribute of the NewsItem object passed into it. For this reason, we are able to redirect the user to the view news item page with the id of the newly created news item.
24.1.5 Test
Stop and start the publisher application with the Tomcat manager application, so that Tomcat reloads the web.xml file and the new class files. Verify that the new functionality works correctly by going to http://localhost:8080/publisher/home and creating an additional news item. You should try entering in an empty title and an empty url to check that validation works correctly. The following figure shows approximately how the create news item page should render.
120
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 25, 2009 07:54 pm
24.1.5 Test
121
The delete method takes a news item instance as its sole argument. However, the delete method only needs the id attribute within the news item instance, which it uses within the where clause of an SQL delete command. Note that like the update method, it is possible that some other user deleted the object just prior to the execution of this delete method. However, in this case we silently ignore this unexpected scenario, because the user intends to delete the news item anyway. However, the application would give the user the impression that he or she deleted the news item rather that it being first deleted by someone else. If this false impression were to have negative consequences in some application scenario, then we would change the behavior of the delete method by throwing a NotFoundException in order to inform calling code of the abnormal completeion of the operation.
122
import org.apache.log4j.Logger; import publisher.data.NewsItem; import publisher.data.NewsItemDAO; public class DeleteNewsItemServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); private RequestDispatcher jsp; public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); jsp = context.getRequestDispatcher("/WEB-INF/jsp/delete-news-item.jsp"); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.debug("doGet()"); jsp.forward(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String idString = req.getParameter("id"); // Check if cancel button was pressed. String cancelButton = req.getParameter("cancel-button"); if (cancelButton != null) { logger.debug("cancel button pressed"); resp.sendRedirect("view-news-item?id=" + idString); return; } NewsItemDAO newsItemDAO = new NewsItemDAO(); Long id = new Long(idString); NewsItem newsItem = newsItemDAO.find(id);
123
The first thing we do inside doPost is to check for the cancel button. If pressed, we redirect the user to the view-news-item page so that he can verify that the news item has not been deleted. If the cancel button was not pressed, we perform a find on the news item because we have designed the DAO delete method to take a NewsItem object. In case another user deleted the news item already, we check to make sure the news item is not null. If not null, we pass it to the delete method of NewsItemDAO. Finally, we redirect the user to the list-news-items page so that he can verify that the news item was deleted.
Notice that we pass the id of the news item through a hidden input element.
25.1.6 Test
Stop and start the publisher application with the Tomcat manager application, so that Tomcat reloads the web.xml file and the new class files. Verify that the new functionality works correctly by going to http://localhost:8080/publisher/home and deleting a news item. You should also verify that the cancel operation works correctly. The following figure shows approximately how the create news item page should render.
124
25.2 Exercises
1. Modify the list-news-item page, so that the url of the news item is displayed along with the news item title. 2. Enter the URL http://localhost:8080/publisher/view-news-item?id=9999 into your browser, and observe what happens. In our code, we do not handle the case when a user may type in an invalid news item id. There are many possible ways to handle this problem. One possible way to handle the problem is to simply redirect the user to the list-news-item page. This can be done with the following command:resp.sendRedirect("list-news-item"); To solve this problem, you will also need to research the java docs for the ResultSet class. 3. In the previous exercise, you look at how a user can deliberately input invalid data to make the application malfunction. However, it is possible that the web application malfunction in the same way in another scenario in which the user is not trying to deliberately break the system. Explain the scenario in which the user innocently clicks on a news item link in the list-news-item page, and is sent to the view-news-item page with an invalid id. (Hint: the scenario requires that there are at least two users logged in at the same time, or that one user is logged in with the same username in two different browser instances.) 4. Re-organize the architecture of the system by creating a ParentServlet that all other servlets extend, and move common functionality into the parent class. In particular, move the jsp variable, dataSource variable, and close method into ParentServlet. (Change the modifier from private to protected, so that these can be accessed by subclasses.) There is a lot of redundant logic in the init methods. Move as much of this code as possible into the parent servlet. One way to do this is to declare an init method in ParentServlet that takes the path to the jsp as a String. In the init methods of the child classes, invoke the parent's init method with something like the following.
init("/WEB-INF/jsp/edit-news-item.jsp");
25.1.6 Test
125
Java Web Programming with Eclipse Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 19, 2009 02:32 pm
25.2 Exercises
126
127
Before implementing the solution to this problem, carry out the senario to set how the application malfunctions.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 13, 2009 06:01 pm
128
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 13, 2009 05:40 pm
129
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 13, 2009 12:40 pm
130
If you get a message that the command is unknown, then you need to provide the full pathname to the keytool executable (or add the bin folder in your jdk installation to the path variable in your environment). Also, if you are using Windows Vista, you probably need to be administrator to write the keystore file into the conf folder.
131
The caret symbol (^) and backslash (\) at the end of each line in the above commands indicates line continuation for Windows and Linux, respectively. The keytool command is part of the Java SDK. If your system only contains the Java JRE, then you will need to install the JDK to get access to this command. The CN variable in the certificate should contain the domain name of your server. Because you are running Tomcat and your browser from the same machine, setting the CN variable to localhost as done above is OK. However, if you wanted to access Tomcat from a remote machine, you would need to replace localhost with the domain name of the machine on which Tomcat is running.
The following is an example Connector element that sets up HTTPS on port 8443.
<Connector port="8443" maxThreads="200" minSpareThreads="5" maxSpareThreads="75" enableLookups="true" disableUploadTimeout="true" acceptCount="100" scheme="https" secure="true" SSLEnabled="true" clientAuth="false" sslProtocol="TLS" keystorePass="changeit" keystoreFile="conf/keystore" />
If the above configuration fails for you, it may be that you changed the passwords from changeit to some other value when you ran keytool. In this case, add the following attribute to the above connector element.
truststorepass="storepass-value" keystorePass="keypass-value"
If you are running Windows Vista, regular users may not have the privileges to modify server.xml. In this case, you need to edit server.xml as adminstrator. To do this, right click on wordpad in the Windows start menu and select run as adminstrator.
29.1.6 Test
Test your configuration by starting (or restarting) Tomcat and pointing your browser to https://localhost:8443/publisher/home. A security alert is presented to you because the browser you are using 29.1.4 Running keytool under Linux and Mac OS X 132
Java Web Programming with Eclipse does not contain in its trust store the certificate you generated for Tomcat, nor does it contain a certificate that was used to sign your certificate. Note that if you want to change the port number used for HTTPS, make sure you change the redirect attribute of the unencrypted connector element in server.xml to your new value.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 16, 2009 05:32 pm
29.1.6 Test
133
Create class UserDAO in the publisher.data package with the following contents.
package publisher.data; import import import import import import java.sql.Connection; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; java.util.LinkedList; java.util.List;
public class UserDAO extends DataAccessObject { private static UserDAO instance = new UserDAO();
134
135
136
The above implementation of the user DAO enables management of user accounts similar to the management of NewsItems. However, for the purpose of developing login and logout functionality, we only need the method findByUserName. The following SQL command creates a table called user that can hold instances of the user class. You should add this to the cdreatedb.sql script in the publisher project.
create table user ( id integer primary key, username varchar(255) unique,
137
In order to get some user accounts for testing, add a few insert commands to the insertdb.sql script. The following is an example.
insert into user (id, username, password) values (4, 'admin', 'admin');
Modify the cleandb.sql script as well to delete the user table. Run the database scripts to rebuild the publisher database with user account information. Make sure that the ant build scripts run without error. Also, use the mysql command line client to verify that the database is recreated correctly.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 13, 2009 12:57 pm
138
Create a class called LoginServlet that extends HttpServlet to handle requests for the login page and requests to process submission of login credentials. The following is an example LoginServlet that will suit our needs.
package publisher.web; import java.io.IOException; import import import import import import import import javax.servlet.RequestDispatcher; javax.servlet.ServletConfig; javax.servlet.ServletContext; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
139
The init method in the login servlet stores a reference to the request dispatcher that is used to forward processing to the login jsp file. The doGet method simply forwards processing to the jsp through the request discpatcher. The doPost method runs when the user submits the login form. The login form has two input fields: one named username and the other named password. The first thing the doPost method does is to get the username entered by the user (with a call to getAttribute on the request object), and then tries to retrieve the persistent User object with this username. If such a user object does not exist, the findByUsername method returns a null 31.1.2 Login Servlet 140
Java Web Programming with Eclipse value. In case of a null value, doPost sets a message attribute in the request object and then forwards to the login jsp so that the login form is re-displayed to the user. However, this time, the user also sees a message saying that the authentication has failed. The jsp file got this failure message from the message attribute stored within the request object. Note that after forwarding to the jsp, we return from the doPost method. It is a common mistake to forget to do this. If you do make this mistake, the servlet will continue processing the request after the jsp has already returned a response to the browser. This usually results in an exception when the servlet tries to send something else to the browser. If on the other hand the username corresponds to a user in the user table of the publisher database, the findByUsername method wil return an instance of the user class with the username, pasword and id fields taken from the database. In this case, doPost needs to check that the password submitted by the user matches the password retrieved from the database. We use the equals method of the string class to compare the 2 passwords. If we were to have used the comparison operator == the comparison would be done between the string references rather than the string values. In other words, the comparison would check to see if the 2 string references point to the same object in memory. If the 2 passwords are not equal, doPost returns exactly the same message that it does for the case that the username is not known. It is a security flaw to report to the user that the password is wrong or that the username is wrong, because this enables an attacker to confirm the existence of usernames in the system. If the 2 passwords match, then the user has successfully authenticated to the system. In this case, we store a value in the session object that indicates the identity of the user. In our case, we will store the id of the user in the session. After doing this, we redirect the user to the home page. Note that we could have forwarded to the home jsp instead of redirecting. However, when forward execution to the jsp, the url displayed to the user will not correspond to the page they are viewing. We can avoid this potential confusion by redirecting the browser to the home page, which means we return an HTTP redirection response to the browser to tell it that it should retrieve content from a different URL. To understand how attaching the user's identity to the session object works for authentication, you need to understand how the web container creates and uses the session object. The first time the user goes to the web site, the web container returns a set-cookie header along with the HTML comprising the web page. The set-cookie header has a duration attribute set to session to let the browser know that the cookie value is to be used to maintain a session. A session is a sequence of client-server interactions that can be thought of as comprising a conversion between the client and the server that is distinct from conversions that have taken place in the past or will take place in the future. The set-cookie header contains a long random string of characters that are difficult to guess, so that attackers can not hijack the session by pretending to be someone else. The browser caches this cookie for as long as it runs. When the browser shuts down, it generally deletes all its session cookies. Each time the browser sends a reuquest message to the server, it will attach the session cookie value in a cookie header. Therefore, each time the server gets a request, it uses the cookie value to determine which session, or conversion, this request is a part of. The web container provides an instance of the HttpSession class to the web application for each session. Session data is not maintained forever by the server; if a given session cookie is not received by the server after a session time-out value, the server will delete the session data from its memory. Subsequent requests containing that cookie value will result in a new session cookie value sent back to the browser. This is the reason you are logged out of a site automatically after a long period of inactivitiy, even though you did not restart your browser. In Java, the session object is retrieved by calling the getSession method of the request object passed into doGet or doPost. By storing the user's id in the session object, the code running in the application can determine who it is interacting with. In the jsp folder, create login.jsp with the contents of the following listing.
141
In the jsp given above you can see the scriptlet of Java code that pulls out the value associate with the name message. If the value is not null, it means the servlet set a message to display. In this case, the jsp writes the message value into the output stream into which the HTML is being written and transported to the browser. Start and stop the application with the manager application so that Tomcat reprocesses the deployment descriptor and loads new class files. Go to http://localhost:8080/publisher/login, type in the username and password of a user and verify that you are sent to the home page. Go back to the login page, type in an incorrect username and password, and verify that you are returned to the login page with an error message.
142
import org.apache.log4j.Logger; public class LogoutServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.debug("doGet()"); HttpSession session = req.getSession(); session.invalidate(); String url = "login"; resp.sendRedirect(url); } }
Verify that login/logout function works. Logging in should bring you to the home page; logging out should bring you back to the login page. At this point, logging in and out has not real effect on the application, because users can access every web page regardless of whether they are logged in or out. In the subsequent section, we will add a filter that filters out requests for web pages that we want to show only to logged in users.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 19, 2009 02:57 pm
143
The security-constraint element ensures that access to the login servlet is done over https. (Https is the standard mechanism for providing confidentiality.) The filter element tells the servlet container to pass all requests to the application through the security filter rather than to the target servlet. The security filter then decides whether to pass the request message to the target servlet or redirect the user to the login page. In the publisher.web package, create a java class called SecurityFilter with the contents of the the following code.
package publisher.web; import java.io.IOException; import import import import import import import import import javax.servlet.Filter; javax.servlet.FilterChain; javax.servlet.FilterConfig; javax.servlet.ServletException; javax.servlet.ServletRequest; javax.servlet.ServletResponse; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
144
The init method implemented above does nothing but is needed in the code because the it is a method in the Filter interface. All methods in interfaces must be implemented, so we provide a empty method. Similary, we provide an empty implementation of the destroy method. The web.xml code given earlier configure this filter to process all requests that come into this application. If the user is not logged in, then we will send the user to the login page. In this way, users can not access any application functionality other than the login page until they authenticate themselves to the system. The doFilter method of the above filter is called for every requested resource. The first thing we do is check to see if the requested resource is for the login page. Requests for the login page should always be honored, so in 32.1 Security Filter 145
Java Web Programming with Eclipse this case, we permit the request to be processed by the servlet attached to the incoming request by calling doFilter on the chain object. The chain object represents the chain of processors that will be used for the incoming requests. After calling doFilter on the chain object, we return because at this point, the login servlet would have processed the request. In addition to login requests, we also want to permit requests for the news feed. This allows anyone to view the news feed. What we want to restrict is access to the functionality that allows users to create, edit and delete news items. If the request is not for login and not for the news feed, then we need to check to see if the user is logged in. We do this be looking to see if the user's id is stored in the session. If the user's id is in the session, we allow the request to be processed by calling doFilter on the chain object. If the user's id is not in the session, then we redirect the browser to the login page. Stop and start the publisher application and then perform the following tests with a fresh browser instance. 1. Verify that login and logout functions work correctly. 2. After doing a logout, try to access a protected resource without logging in. For instance, try to access http://localhost:8080/publisher/home. Verify that the application redirects you to the login page rather than sending you the home page. If it appears that you can still access a protected resource, then the browser is presenting to you a cached version of the web page. To see that this is the case, click on the reload button of the browser and see that you are redirected to the login page.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 17, 2009 07:54 pm
146
147
Notice that SecureDigester has a main method. This allows you to run the digester outside the web application for the purpose of generating digests of passwords to include in test data. The digest function of SecureDigester is the public entry point into the class that will be called by the login servlet to computer password digests. As you can see from the code, the digest method uses the MessageDigest class that is part of the core Java API. MessageDigest has a factory method called getInstance that takes a string that names the hash function to use. In our case, we specify SHA, which is a commonly used secure hash function. The code passes the plaintext string into the update method of the message digest object as a byte array of UTF-8 character codes. Then, the digest method is invoked on the message digest object in order to compute the SHA digest of the byte array. This returns a byte array, which is then transformed into a string by a call to the locally defined byteArrayToHexString. It is this string that the application uses as its version of the password. Now, modify the login servlet by replacing the password checking code with the following code. Remember to organize imports to resolve the name SecureDigester.
String password = req.getParameter("password"); if (password == null) { logger.debug("authentication failed: no password"); req.setAttribute("message", "Authentication failed."); jsp.forward(req, resp); return; } String passwordDigest = SecureDigester.digest(password); if (!user.getPassword().equals(passwordDigest)) { logger.debug("authentication failed: bad password"); req.setAttribute("message", "Authentication failed."); jsp.forward(req, resp);
148
At this point, in order to login, we need to replace the passwords in the database with their digests as computed by the secure digester class. To do this, we run the secure digester class as a stand-alone program and pass in the password as a command line argument to the program. To do this inside of Eclipse, we create a run configuration that specifies the secure digester class as the entry point of execution and enter the password that we wish to encrypt as a program argument. Form the main mennu, select Run ... Run Configurations. Navigate to the publisher project and secure digester main class if these fields are not already set correctly. The following screen shot shows the reult.
Select the arguments tab and enter into the program arguments box the password that you wish to encrypt. See the following screen shot shows the string admin being passed in as the password to digest.
149
After running the secure digester to encrypt a password, look in the console view to see the result. If you entered the string admin, the program would generate the following output in the console view.
admin -> D033E22AE348AEB5660FC2140AEC35850C4DA997
Open the insert_data.sql script and replace the password value of the user with the hex string produced by the secure digester and run the database build file to re-build the database. Restart the publisher application and verify that the application works correctly.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 24, 2009 01:13 pm
150
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified February 13, 2009 07:40 pm
151
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 12:54 pm
152
Conceptually, a wiki contains every possible page, which means that all requests for pages are considered valid. If the user requests a page that has never had content added to it, then the user sees a blank page. In the database, only pages that have non-empty content are stored. A page with only white space is considered empty, and is thus not stored in the database. If a user wishes to delete a page, he or she sets its contents to empty, and the application will then delete the page from the database. Note that in wiki systems such as the open source project used by Wikipedia, called MediaWiki, the history of edits to pages are saved so that users can restore previously deleted content or simply view previous versions of a page. In our simple wiki, we will not store previous versions of pages, which could be a great inconvenience in a real usage scenario. In our wiki system, users see an edit link and a publish link on each page. To change the contents of the page, whether it is an initial entry or a mofification to existing content, the users selects the edit link and transitions 36 Wiki Application (continued) 153
Java Web Programming with Eclipse to an edit page. In the edit page, the user can modify the contents of the page and then either save or cancel changes. In both cases, the user is brought back to the view page. The above diagram actually shows two versions of the view page: one with a publish link and one with an unpublish link. In this wiki system, we will be able to create and delete news feed entries in the publisher application that refer to wiki pages. If a given wiki page is not registered with the publisher application, then the publish link is shown. If the user clicks on the publish link, he or she is brought to the publish page, which is a confirmation window. If the user confirms the publish operation, the system returns the view page with the unpublish link to indicate that the page is in the news feed and to give the user the ability to remove the page from the news feed. If the user cancels the publish operation, he or she is brought back to the view page with the publish link. The unpublish link goes to the unpublish page, which is also a confirmation page. In this chapter, we will build all the above functionality, however we will implement the publish and unpublish operations as stubs. The term stub is used to describe a function that is declared and callable, but has no effect; it is used as a placeholder for the real implementation to be done at a later time. In the chapter that follows, we implement the publish and unpublish operations as web services in the publisher application. The wiki application will then invoke these web services to create and delete news feed entries for wiki pages.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 01:24 pm
36.1 Overview
154
Similar to the publisher project, you should create a folder called database to store database creation scripts and the ant build file to run them. To begin, copy the database folder in the publisher project into the wiki project. In the subsequent steps, we will modify these copied files to work correctly for the wiki application. In the database folder, modify build.xml so that you operate on the wiki database rather than the publisher database. To do this, you only need to modify the property element that sets the value of the mysql.params attribute. The property element should appear as follows.
<property name="mysql.params" value="-u wiki -p1234 -D wiki" />
Replace the contents of createdb.sql with the contents of the following listing. 37.2.1 createdb.sql
create table page ( name varchar(255) primary key, content text not null, published int default 0, published_id varchar(255) );
155
Java Web Programming with Eclipse The name column will hold the name of the wiki page. We use the wiki page name as the primary key rather than using a separate integer id as we did in the publisher application. Using page name as primary key works, because page names need to be unique, which is the main requirement for data to serve as a primary key. The name column has datatype varchar(255), which means that this column will hold variable lengths character strings that can not exceed a length of 255. Varchar columns can be used as primary keys. The content column will contain the character data that comprises the wiki pages; it has datatype text, which allows for the storage of a large number of characters. Text columns can not be used as primary keys. The published column is an integer that will hold a zero or a one, where zero indicates that the page has not been added to the publisher application and one indicates that it has. The published column defaults to 0, meaning that if a value for this column is not specified when a new row is inserted into the wiki page table, then the published column will default to 0. The published_id column holds the id of the news item in the publisher application that references the wiki page represented by this row. If a given page is not published, the state of the published_id column has no meaning to the application. Modify insertdb.sql, so that you create at least two sample pages. You only need to specify values for the name and content columns because the published column defaults to 0, which represents false, and the value of published_id will not be used when published is false. You should create a row to represent the page whose name is the empty string, because this will be the page with no name and can serve as the start page in the wiki system. Use the contents of the following listing for insert_data.sql. 37.2.1.1 insertdb.sql
insert into page (name, content) values ('', '<h1>Nameless Page</h1><a href="hello">hello page< insert into page (name, content) values ('hello', '<h1>Hello Page</h1><a href=".">nameless page
Notice that in the above 2 insert statements we store HTML content directly in the database. Normally in a wiki application users do not enter HTML directly into the application. Instead, they enter character data that is annotated with wiki markup conventions. An example of wiki markup is to use apostrophes to italicize words. The first of the above insert statements creates a page with name equal to the empty string. We refer to this page as the nameless page, or the root page. Inside the nameless page there are 2 links. The first link goes to a page with name hello, which is a nonempty page created by the second insert command. The second link in the nameless page goes to a page called nowhere, which does not exist in the database. When the user follows the link to the nowhere page, he or she will see a blank page that can be modified. Finally, modify cleandb.sql with the contents of the following listing. 37.2.1.2 cleandb.sql
drop table if exists page;
The above statement is not generic SQL syntax. The if exists [page] part of the statement is supported by MySQL, but is not necessarily support by other database systems. This MySQL extension to the SQL definition is convenient because one can issue a drop table command for a table that may not exist. Using this exension, however, breaks the portability of our application. If we want to use another database system, we would most likely need to modify this script. Run the all target of the build file to create and populate the page table of the wiki database.
37.2.1 createdb.sql
156
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 01:16 pm
37.2.1 createdb.sql
157
The page class is simply a container of information; it contains no logic other than that needed to provide access to its data members. Instance of classes such as the page class are sometimes referred to as value objects because that simply represent data without behavior. The complete listing of the page class is as follows. 38.1.3.1 Page.java
package wiki.data; public class Page { private String name; private String content; private boolean published; private String publishedId;
158
We could have avoided implementing the accessor methods (getters and setters) in the page class by simply declaring the member variables public. However, this is a bad idea for 2 reasons. First, making member variables private is a common coding convention (called the JavaBean convention) followed by the majority of Java programmers, so deviating from the convention makes the code less readable by a wider audience. Second, the choice of accessor name is necessary in order to use the JSP expression language. For example, suppose you are in a jsp file and have a variable called wikiPage that contains a reference to an instance of a wiki page. To write the name of the wiki page into the outgoing stream of HTML, you could simply use the following expression.
${wikiPage.name}
The expression language processes the above expression by capitalizing the n in name to become Name and then it prepends get to this, resulting in the string getName. The expression language then uses this string to get an instance of the getName method of the page class. The ability is provided by what is referred to as the reflection API, which is available in managed execution environments in which virtual machine code runs inside a virtual machine. Systems other than the JSP expression language, such as Hibernate for example, rely on the JavaBean convention for naming getter and setter methods. Thus to avoid interoperability problems with other systems, one should adhere to the convention. Note that the above exmaple is not really shorter than what is possible without the expression language. For example, the following scriplet is equivalent to the above example.
<%= wikiPage.getName() %>
159
import javax.sql.DataSource; public class DataAccessObject { private static DataSource dataSource; public static void setDataSource(DataSource dataSource) { DataAccessObject.dataSource = dataSource; } protected static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } } protected static void close(Statement statement, Connection connection) { close(null, statement, connection); } protected static void close(ResultSet rs, Statement statement, Connection connection) { try { if (rs != null) rs.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (SQLException e) { throw new RuntimeException(e); } } }
The data access object parent class is simpler than the one used for the publisher application because it does not to include code that generates unique integers for use as primary keys.
160
public class PageDAO extends DataAccessObject { private static PageDAO instance = new PageDAO(); public static PageDAO getInstance() { return instance; } private Page read(ResultSet rs) throws SQLException { String name = rs.getString("name"); String content = rs.getString("content"); boolean published = rs.getBoolean("published"); String publishedId = rs.getString("published_id"); Page page = new Page(); page.setName(name); page.setContent(content); page.setPublished(published); page.setPublishedId(publishedId); return page; } public Page find(String name) { ResultSet rs = null; PreparedStatement statement = null; Connection connection = null; try { connection = getConnection(); String sql = "select * from page where name=?"; statement = connection.prepareStatement(sql); statement.setString(1, name); rs = statement.executeQuery(); if (!rs.next()) { return null; } return read(rs); } catch (SQLException e) { throw new RuntimeException(e); } finally { close(rs, statement, connection); } }
public void update(Page page) { PreparedStatement statement = null; Connection connection = null; try { connection = getConnection(); String sql = "update page set content=?, published=?, published_id=? wh statement = connection.prepareStatement(sql);
161
162
If you have build errors, make sure that you have included servlet_api.jar in the project build path.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 01:18 pm
163
39.1.2 JSP
Within the web/WEB-INF folder, create a new folder called jsp. Within the jsp folder create a file called view-page.jsp with the contents of the following listing. 39.1.2.1 view-page.jsp
<jsp:useBean id="wikipage" scope="request" type="wiki.data.Page" /> <html> <head> <title>Wiki</title> <link rel="stylesheet" type="text/css" href="../styles.css" /> </head> <body> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="../images/logo.gif"></td> </tr> <tr> <td id="upper-bar"> <div id="upper-menu"> <a href="../edit/${wikipage.name}">edit</a> | <% if (wikipage.isPublished()) { %> <a href="../unpublish/${wikipage.name}">unpublish</a> <% } else { %> <a href="../publish/${wikipage.name}">publish</a> <% } %> </div> </td> </tr> <tr> <td id="lower-bar"> <div id="layout"> ${wikipage.content} </div> </td> </tr> </table> </body>
164
Observe that the page is parameterized by a single variable, wikipage. Before forwarding to this JSP, the servlet constructs the wikipage instance and places it in request scope by associating the name wikipage with an instance of the page class. We avoid using the name page for this purpose because this is a reserved identifier used by JSP to reference something called the JSP page object. The view page uses a table to organize the layout of the page. After the useBean element at the top of the JSP, the next instance of dynamic content is the construction of an edit link. In this edit link, we add the name of the wiki page that we are viewing. When the user clicks the link to edit the page, the browser sends a request with the string edit/ followed by the wiki page name. After constructing the edit link, the JSP file contains a conditional expression that test whether or not the page is published in the publisher application. If the page is published, then the JSP generates a link that goes to the unpublish servlet. If the page is not published, the JSP generates a link that goes to the publish servlet. These two servlets will be constructed in a later section. The last piece of dynamic content to appear in the view jsp file is the page content. Notice that the image tag refers to a logo file in the images folder. This logo will be displayed as the page banner. You should create this folder and place a logo file in there. Also notice that the JSP contains in the HTML head section a reference to a style sheet. You should create this file in the web folder with the following content. 39.1.2.2 styles.css
h1 { color: #000088; } #layout { margin: 1em; } #upper-menu { margin: 0.5em; text-align: right; } #upper-bar { background-color: #E6E6FA; } #lower-bar { background-color: #F5F5DC; }
39.1.2 JSP
165
import org.apache.log4j.Logger; import wiki.data.Page; import wiki.data.PageDAO; public class ViewPageServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); private RequestDispatcher jsp; public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); jsp = context.getRequestDispatcher("/WEB-INF/jsp/view-page.jsp"); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.debug("doGet()"); String pathInfo = req.getPathInfo(); String name = pathInfo.substring(1); logger.debug("Page requested: " + name); Page page = new PageDAO().find(name); if (page == null) { logger.debug("page doesn't exist; creating empty page"); page = new Page(); page.setName(name); page.setContent(""); page.setPublished(false); } req.setAttribute("wikipage", page); jsp.forward(req, resp); } }
In a manner similar to the servlets in the publisher application, we override the init(ServletConfig) method in order to set the value of the request dispatcher that we will use to forward execution to the JSP. The first thing we do after writing a log message is to determine the page name being requested b ythe user. We call getPathInfo on the request object to get the string within the url that follows /view. Because this string begins with a slash, we remove the slash with the substring method. This leaves the name of the wiki page. We print the page name in the log file, and then we use the name to retrieve the page object from the database.
166
Java Web Programming with Eclipse If the page is not in the database, the page DAO will return null. In this case, we create a new page instance, set its name property to the page name being requested. We also set the page content to the empty string and the publsihed attribute to false. After we have either retrieved an existing page or creted a new empty one, we put the page object in request scope by associating it with the name wikipage. The JSP will now be able to access the information it needs from this page object.
<?xml version="1.0"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4 version="2.4"> <listener> <listener-class>wiki.web.Init</listener-class> </listener> <servlet> <servlet-name>view-page</servlet-name> <servlet-class>wiki.web.ViewPageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>view-page</servlet-name> <url-pattern>/view/*</url-pattern> </servlet-mapping> </web-app>
39.1.5 Deploy
Deploy the wiki application to the path /wiki in a manner similar to how you deployed the publisher application. The context element will look like the following. Make sure you replace ${WORKSPACE} with the path to your eclipse workspace. Additionally, make sure the database parameters are correct.
<Context path="/wiki" docBase="${WORKSPACE}\wiki\web"> <Resource name="datasource" type="javax.sql.DataSource" auth="Container" maxActive="10" maxIdle="3" maxWait="10000" username="wiki" password="1234" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/wiki?autoReconnect=true" /> </Context>
If you are not sure that you deployed the application correctly, then check to see that deployment succeeded by looking in ${TOMCAT}/conf/Catalina/localhost. You should see the file wiki.xml. Open this file and verify that it is identical to the wiki.xml given above that you placed in your wiki project folder.
167
Java Web Programming with Eclipse If deployment succeeded, but the application is still not working correctly, then look in all the log files for messages. If there is an error related to connecting to the database, make sure that all the arguments in the context element in wiki.xml are correct.
39.1.6 Test
Go to http://localhost:8080/wiki/view/ to view the page with no name as shown in the following screen shot. Click on the hello link and see that you go to the hello page. Click on the nowhere link and see that an empty page is generated. 39.1.6.1 View page
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 01:30 pm
39.1.5 Deploy
168
The first line tells the JSP translator to generate code that retrieves the value of a page obejct that has been associated with the key wikipage in the request object. The form element does not contain an action method, so the browser will submit form data to the same URL that it used to retrieve the form data. The first two input elements in the form are save and cancel buttons. The save button has the attribute name set to save-button and the cancel button has the attribute name set to cancel-button. When the edit page servlet receives a submission from the browser, it will check for the presence of a parameter that has name save-button or cancel-button, and will thus be able to determine which button the user clicked. The third input element is a hidden element with the page name set as the value of name. Browsers do not display hidden input elements to the user. Hidden input elements are used to carry information that is sent to the server with the rest of the form data. In this case, the hidden element is used to send the name of the page to the edit servlet. This is neccessary because the edit servlet needs to know which page is being updated.
169
Java Web Programming with Eclipse The forth element is also a hidden element. It is used to carry the state of the published attribute. This information is actually not needed at this point, because once the edit servlet has the page name, it can determine the state of the published attribute. The final input control within the form is a textarea element. This element displays as a multi-line editable text box. The current contents of the given page will be displayed in this text area.
import org.apache.log4j.Logger; import wiki.data.Page; import wiki.data.PageDAO; public class EditPageServlet extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); private RequestDispatcher jsp; public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); jsp = context.getRequestDispatcher("/WEB-INF/jsp/edit-page.jsp"); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.debug("doGet()"); String pathInfo = req.getPathInfo(); String name = pathInfo.substring(1); logger.debug("Page requested: " + name); Page page = new PageDAO().find(name); if (page == null) { logger.debug("page doesn't exist; creating empty page"); page = new Page(); page.setName(name); page.setContent(""); page.setPublished(false); } req.setAttribute("wikipage", page); jsp.forward(req, resp); }
170
The doGet method of the edit page servlet is identical to the view page servlet. In both servlets, the doGet method must retrieve or create a wiki page object and pass this to its JSP. In the case of the view page servlet, the JSP displays the contents of the wiki page within a div element. In the case of the edit page servlet, the JSP places the contents of the page in an editable text area within a form element. So although the two different JSPs use the wiki page object in different ways, they both need the same object. The view page and edit page servlets differ in that the edit page servlet implements a doPost method, which the view page servlet does not have. The doPost method of the edit page servlet receives form data from the browser when the user submits changes to the page contents. The first thing the doPost method does is extract references to the form data and stores them in variables. After extracting the form data, the doPost method checks to see if the cancel button was clicked, in which case the user does not want to save changes to the page. In this case, we return an HTTP redirect message to the 40.1.3 The Edit Page Servlet 171
Java Web Programming with Eclipse browser telling it to request the view page for the page that was in the edit window. We return after sending this message to the browser, because no other work is needed. If on the other hand the user is not canceling the edit, we need to store changes to the page in the database. We do this by constructing a new page object with the data submitted by the user. If the user is submitting an empty string, or a string of blank characters, then we delete the page from the database. We do this by calling the delete method of the page DAO. Note that we do not need to check to see whether or not the page exists in the database because if the page does not exist, the SQL delete command will have no effect and will not throw an exception. If the user is submitting non-empty page content, then we need to check to see whether or not the page exists. If the page does not exist, we call the create method of the page DAO, passing in the new page to create. If the page exists, then we call the update method of the page DAO. The create method uses an SQL insert command and the update method uses an SQL update command. It is possible for one user to delete a page from the database just before another user saves changes to the page. In this case, the update method of the page DAO will throw an exception because it submitted an update command for a row that doesn't exist. Further work would need to be done with the wiki application to handle this problem without displaying an exception to the end user.
Note that the url pattern is similar to the one used to direct requests to the view page servlet. Although other approaches are possible, we use this one in order to match with the way we route to the view servlet.
40.1.5 Test
Stop and start the wiki application with the manager application. Then test the new functionality by going to http://localhost:8080/wiki/view/ and trying to edit the page. The edit page should look like the following screen shot. 40.1.5.1 Edit page
172
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 01:32 pm
40.1.5 Test
173
174
175
The doGet method of the publish page servlet is requested by the browser when the user clicks on the publish link that appears within the view page. The doGet method as implemented above allows empty pages to be published. For this reason, the method must create an instance of the wiki page class if the find method of the page DAO returns null. The doGet method forwards execution to the publish page JSP, which asks the user to confirm the operation. In the publish page JSP, the user either clicks the publish button or the cancel button. Regardless of whether the publish or cancel buttons are clicked, the doPost method needs to know which page the user is on. If he or she clicks the cancel button, the doPost method redirects the the user back to the view page. The user can verify that the page is not published by seeing that the publish option is still available for the page. If the user is confirming the publish operation, the next thing we do is to retrieve an instance of the page from the database. If the page does not exist in the database, it mean the user is publishing an empty page. We do not allow publishing of blank pages, so we redirect the user to the view page. However, the user will see the publish link in the view page, which may implies that page is not published. Additionally, if the page is already published, we do the same thing. If the page exists in the database, then we invoke the publish web service of the publisher application, which will be implemented in the next chapter. We place all of the logic for this web service invocation in a private method called publish. When we invoke the publish service, we will obtain a news feed id as a result. To prepare for this evetuality, we create a news feed id, called publishedId, and set it to the artificial value 3 for testing purposes. Note that we declare the publish method as throwing an exception to prepare for later code that communicates with the publisher application and thus will be capable of throwing exceptions related to communciation, XML document procesing and other sources of exceptions. After invoking the publish web service, we need to save the published id with the rest of the page data and we need to set the isPublished property of the wiki page to true. After doing this, we redirect the user to the view page, where he can now see the unpublished link, which is implicit confirmation of the publish operation.
176
41.1.5 Test
Stop and start the wiki application with the manager application. Then test the new functionality by going to http://localhost:8080/wiki/view/ and clicking on the publish link. Verify that the publish confirmation page displays correctly as shown in the following screen shot. 41.1.5.1 Publish page
Try canceling the operation and then verifying that the publish link is displayed in the view page. The try the publish link again but this time confirm the publish operation. Verify that the link turns to unpublished as shown in the following screen shot. 41.1.5.2 Publish menu becomes unpublish
41.1.5 Test
177
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 24, 2009 01:10 pm
41.1.5 Test
178
import org.apache.log4j.Logger;
179
180
The doPost method invokes the publisher's web service inside the unpublish method, which we will implement at a later time.
42.1.5 Test
Stop and start the wiki application with the manager application. Then test the new functionality by starting at http://localhost:8080/wiki/view/. Try all possible combinations to verify that the application functions correctly. The unpublish confirmation page is shown in the following screen shot. 42.1.5.1 Unpublish page
181
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 20, 2009 01:47 pm
42.1.5 Test
182
Test that exceptions are now written to your log file by introducing a bug into your code.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 23, 2009 01:45 pm
183
44 Web Services
44.1 Chapter Contents
Overview Add a Web Service to Publish News Items Invoke the Publish Service from the Wiki Application Implement and Consume the Unpublish Service Add Security Mechanisms Exercises
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 12:19 pm
44 Web Services
184
Java Web Programming with Eclipse publish and unpublish operations that users of the wiki application can invoke so that users of the wiki application can publish and unpublish wiki pages to and from the RSS news feed of the publisher application. The following diagram illustrates the interactions between the various systems and their sub-components.
The stick figures above represent human access to the systems via browsers. When users of the wiki application invoke the publish operation on a given wiki page, the wiki application composes an XML document to serve as a web service request message and sends this message to the publish web service of the publisher application. The request message contains the link to the wiki page and the wiki page title. The publisher application generates a unique id to represent the new news item, and then adds this id, the link and title information to its database. The publisher application then places the id in a simple XML document to be used for a web service response message, which it returns to the wiki application. The wiki application saves the returned id in its record for the wiki page being published. This returned id can be used later to unpublish (or delete) the wiki page from the RSS news feed. After a wiki page is published in the manner just described, users visiting the home page of the website application will see the linkable title of the wiki page. This is accomplished in the HomeServlet of the website application, which retrieves the RSS document from the publisher application. If the website were to be a high volume destination, requesting the RSS news feed for each request fot the website home page would result in too many redundant requests for the publisher's news feed. In this case, the developer could cache the RSS document and construct its home page from the cache in order to reduce this outgoing traffic and reliance on the publisher site. There are many ways to implement this improvement. The website could rely on a simple periodic check in which it requests the fresh version of the RSS document. Another possibility is for the website to register itself as a downstream client of the publisher's news feed and wait for the publisher to deliver to it revisions to the RSS document. In this situation, we say that the publisher pushes content to its clients. The RSS 2.0 protocol provides a means to accomplish this push mechanism.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 12:29 pm 45.1 Overview 186
45.1 Overview
187
import publisher.data.NewsItem; import publisher.data.NewsItemDAO; public class PublishNewsItemService extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.debug("doPost()"); // Read the XML request document. BufferedReader br = req.getReader(); SAXBuilder builder = new SAXBuilder(); Document requestDocument = null; try { requestDocument = builder.build(br); } catch (JDOMException e) { throw new RuntimeException(e); } // Extract title and link from request. Element item = requestDocument.getRootElement(); Element titleElement = item.getChild("title"); String title = titleElement.getText(); Element linkElement = item.getChild("link"); String link = linkElement.getText(); // Create a news item from submitted data.
188
Observe that the publish servlet implements the doPost method and does not implement the doGet method. This means that clients of the publish web service will submit requests using HTTP POST messages, which means they will submit news item data in the body of the HTTP request messages. We will follow the most common convention, which is to structure the submitted data as an XML document. An example XML document that the client will submit is as follows.
<item> <title>Yahoo home page</title> <link>http://yahoo.com/</link> </item>
When the doPost method is called, we extract the XML data with the SAXBuilder of the JDOM library. This is done with the following code.
// Read the XML request document. BufferedReader br = req.getReader(); SAXBuilder builder = new SAXBuilder(); Document requestDocument = null; try { requestDocument = builder.build(br); } catch (JDOMException e) { throw new RuntimeException(e); }
The builder takes as an argument a BufferedReader, which provides access to the character data coming in from the client. The builder creates an object representation of the XML document and returns a reference to this object, which is of type Document. The build method of the builder object extracts the data from the buffered reader passed into it and constructs the document object. This operation relies on extracting data from an underlying communications socket, which may fail if there is a network or other communications error. The build operation may also fail if the incoming characters can not be parsed as an XML document. For these reasons, the build operation throws a checked exception that we handled with a try-catch block. 46.1 A Web Service to Publish News Items 189
Java Web Programming with Eclipse After the SAX builder builds an object representation of the submitted data in the form of an instance of the document class, we extract the title and link strings for the news item. To do this, we first obtain a reference to the root element of the request document, and then we access the children of the root elememnt, which are the title and link elements.
// Extract title and link from request. Element item = requestDocument.getRootElement(); Element titleElement = item.getChild("title"); String title = titleElement.getText(); Element linkElement = item.getChild("link"); String link = linkElement.getText();
After we have the title and link for the news item, we use it to create an instance of the NewsItem class. This news item instance is passed into the create method of the newsItemDAO in order to store the news item data in the database.
// Create a news item from submitted data. NewsItem newsItem = new NewsItem(); newsItem.setTitle(title); newsItem.setUrl(link); new NewsItemDAO().create(newsItem);
The create method has a side effect of creating and setting the id of the news item. The client needs this id in order to remove the news item from the RSS feed at some point in the future. For this reason, we return the id of the newly created news item to the client. To return the news item id to the client, we follow the convention that data be exchanged within XML documents. The following XML document is an example of what we would return to the client, assuming that the id of the newly created news item is 3.
<?xml version="1.0" encoding="utf-8"?> <id>3</id>
It is possible to create this XML document simply with the following code.
String responseDocString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<id>" + newsItem.getId() + "</id>";
However, we use JDOM library to create the XML response document in order to provide more consistency in the code and because it provides us with a better foundation to create more complicated documents in the future. The following code is resposible for contructing the XML document comprising the response from the server.
// Create response document with id of newly // created news item. Element idElement = new Element("id"); idElement.addContent(newsItem.getId().toString()); Document responseDocument = new Document(idElement); StringWriter sw = new StringWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.output(responseDocument, sw); String responseDocumentString = sw.toString();
190
Java Web Programming with Eclipse In the above, we construct an instance of the element class to represent the id element that will contain the string representation of the id we created for the news item. Because XML documents must have root elements, the contructor of the document class naturally takes an element in its contructor. This is the reason we pass the id element to the constructor of the document class to create the object the represents our response. We then use the XML outputter class to serialize the XML document into a string. It is this string that we will return to the client. Finally, we return the response document to the client. When doing this, we need to pay attention to the encoding of the characters. The default character encoding for XML is UTF-8, which all XML parsers are required to support. For this reason, it is safest to return the XML document in the UTF-8 character encoding. The following code shows the process of returning the response to the client.
// Return response document. byte[] responseBytes = responseDocumentString.getBytes("UTF-8"); resp.setContentLength(responseBytes.length); resp.setContentType("text/xml"); OutputStream os = resp.getOutputStream(); os.write(responseBytes); os.flush();
We start by invoking the getBytes method of the string representing the request document, passing into this method the argument UTF-8. This returns a byte array containing the raw binary representation of the message data. However, before we send the resulting bytes, we first set the HTTP content length and content type headers by calling the methods setContentLength and setContentType, respectively, on the response object. We then pass this byte array into the write method the output stream from the response object that was passed into our doPost method. When we invoke the write command on the output stream in this way, Tomcat first sends the HTTP status line, followed by the response headers (including our content-length and content-type headers), followed by the bytes in the array. This sequence of actions is important to keep in mind when developing server-side logic; confusion on this point can be the source of incorrect logic. Note that if we omit the content length header in the response, Tomcat will use the chunked encoding format to send the response document. In order to keep the client code simple, we avoid the chunked encoding format by setting the content length explicitly. The following XML fragment needs to be added to the publisher's deployment descriptor to configure the publish servlet.
<servlet> <servlet-name>publish-service</servlet-name> <servlet-class>publisher.ws.PublishNewsItemService</servlet-class> </servlet> <servlet-mapping> <servlet-name>publish-service</servlet-name> <url-pattern>/publish</url-pattern> </servlet-mapping>
Initially, we will allow all clients to invoke the web service; later we will require that clients authenticate to the server. To accomplish this, in the doFilter method of SecurityFilter, add the following lines of code to the correct place in order to allow unauthenticated clients to invoke the web service.
// Allow access to web service. if (servletPath.equals("/publish")) { chain.doFilter(req, resp);
191
At this point, we can not easily test the functionality of the publish web service because a test requires that an XML document be submitted to the publisher application, which is something that a web browser does not do when a form is submitted. (We could use JavaScript to do it using the XMLHttpRequest object.) In the next section, we will be able to test our implementation of the publish service by modifying the wiki application so that it invokes the service.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 01, 2009 12:42 pm
192
Socket socket = new Socket("localhost", 8080); OutputStream os = socket.getOutputStream(); os.write(requestLine.getBytes("US-ASCII")); os.write(hostHeader.getBytes("US-ASCII")); os.write(contentTypeHeader.getBytes("US-ASCII")); os.write(contentLengthHeader.getBytes("US-ASCII")); os.write(connectionHeader.getBytes("US-ASCII")); os.write("\r\n".getBytes("US-ASCII")); os.write(docBytes); os.flush(); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is);
193
When you organize imports on the above code, select the following classes from the lists presented to you. org.jdom.Document java.io.InputStream org.jdom.Element java.io.OutputStream The publish method given above takes a wiki page object as its sole argument. It uses this object to construct a request to publish a news feed that points to the wiki page. To keep the example simple, we include only the title and wiki page link as data in the news feed. We start the implementation of the publish method by contructing variables that represent these two pieces of information: pageName and pageUrl. The next thing we do is create an instance of SAXBuilder. SAX stands for simple API for XML. The SAX builder object is used for constructing XML documents. In our case, we use this object to construct the XML message to send to the publish service of the publisher application, which will contain the title and link for our wiki page. Recall that the document that the wiki application submits to the publisher application contains a single root element called item, which represents the news item being submitted. The following XML document is an example.
<item> <title>Yahoo home page</title> <link>http://yahoo.com/</link> </item>
Under the item element there are 2 children elements that contain text data (rather than sub-elements). The first child element is called title, and it contains within a start tag and an end tag the title of the news item. The second child element is called link, and it contains within a start tag and an end tag the url of the news article.
194
Java Web Programming with Eclipse For each of the child elements, title and link, we create an instance of the JDOM element class. The following shows how we firts create the title element and then assign its contents. To keep the example application simple, we simply use the name of the wiki page for the title of the news item.
Element titleElement = new Element("title"); titleElement.addContent(pageName);
After creating the 2 child elements, we create an element to represent the root element item, and add the 2 child elements to it. This is shown in the following.
Element root = new Element("item"); root.addContent(titleElement); root.addContent(linkElement);
We then create an instance of the JDOM document class to contain the root element as follows.
Document document = new Document(root);
We then create a StringWriter and an XMLOutputter. We pass the XML document and the string writer into the output method of the XML outputter class. The XML outputter writes a serialized version of the XML document into the string writer. We then extract the string that was written into the string writer and prepare to send this string to the publish service.
StringWriter sw = new StringWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.output(document, sw); String docString = sw.toString();
At this point, we have constructed a string that contains the MXL document to send to the service. We are going to write the character comprising this string into the output stream provided through a communication socket object. To prepare for this, we convert the string representation into a byte array as follows.
byte[] docBytes = docString.getBytes("UTF-8");
When converting characters into their byte equivalents, one must decide on a character representation. In our case, we use the UTF-8 representation, which is the default representation for XML documents. The next set of operations is to construct the HTTP header that will precede the XML document in the outgoing stream of bytes.
String String String String String contentLengthHeader = "Content-length: " + docBytes.length + "\r\n"; contentTypeHeader = "Content-type: text/xml\r\n"; hostHeader = "Host: localhost\r\n"; connectionHeader = "Connection: close\r\n"; requestLine = "POST /publisher/publish HTTP/1.1\r\n";
The header of an HTTP/1.1 request message is comprised of a request line followed by 1 or more header lines. In our case, we send the content length, which is the number of bytes in the body of the request message. In our case, the content length is the number of bytes in the byte array representation of the XML document. We also send the content type, which is text/xml. The content type header specifies what is called the MIME-type of the object being transported in the body of the request message, which is a legacy term from the IETF email specifications. We send a host header that indicates the host name of the computer we are sending the message to. The host name header is the only request header that is required to be sent in 47.1 Invocation of the Publish Service from the Wiki Application 195
Java Web Programming with Eclipse version 1.1 of HTTP. The purpose of the host header is to inform the server which host name it resolved to get the server's IP address. This is useful in the case that a server has multiple host names (or virtual hosts). We send a connection header indicating that the underlying TCP connection will be closed by the client after the server returns a response. The request line is the the first line to be sent in an HTTP request. It starts with an HTTP method, POST in our case, followed by the name of a resource on the server, followed by the version of the HTTP protocol being used. We then create a TCP socket connection to the server hosting the publisher application (localhost in our example) and send the HTTP request message to it.
Socket socket = new Socket("localhost", 8080); OutputStream os = socket.getOutputStream(); os.write(requestLine.getBytes("US-ASCII")); os.write(hostHeader.getBytes("US-ASCII")); os.write(contentTypeHeader.getBytes("US-ASCII")); os.write(contentLengthHeader.getBytes("US-ASCII")); os.write(connectionHeader.getBytes("US-ASCII")); os.write("\r\n".getBytes("US-ASCII")); os.write(docBytes); os.flush();
Note that Tomcat in our case is listening to port 8080. For this reason, Tomcat receives the HTTP message that we send (from inside Tomcat). Tomcat will parse the incoming HTTP message and construct an HTTPServletRequest object as a result. By examining the requested resource /publisher/publish, Tomcat determines to route the message to the publish servlet of the publisher application. After sending the HTTP request message to the publisher application, it is time read the response message returned by the service.
InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);
We start by getting a reference to the input stream from the socket, which allows us to read raw bytes being returned to use through the TCP connection represented by the socket. We wrap the input stream in an input stream reader. This class converts the incoming stream of bytes into a stream of characters. The two streams mentioned so far do not do any buffering. We then wrap the input stream reader in a buffered reader, which allows us to read a line at a time. A line is a sequence of characters terminated by a new line character. Also, if the end of stream occurs, then the line can end this way as well. We then enter a loop that reads through the header lines of the HTTP response message. HTTP header lines are terminated by an empty line, which is the condition we use to terminate the loop.
while (true) { String line = br.readLine(); if (line.length() == 0) break; }
Once we are at the start of the HTTP message data, we are ready to parse the XML documment that the service is returning. We do this by calling the build method on the SAX builder object that we used at an earlier point to create the outgoing XML document.
Document responseDoc = null;
196
Recall that the document returned by the service looks like the following, minus any XML prolog (XML syntax preceding the root element).
<id>3<id>
Thus, once we have an object representing the XML document, we simply need to extract the text contents of its root element to obtain the id of the newly created news item.
Element idElement = responseDoc.getRootElement(); String id = idElement.getText(); br.close();
We then close the buffered reader, which closes the underlying input stream, and we return the extracted id to the calling code. You should add the publish method to the publish page servlet of the wiki application and replace the code that in the doPost method that sets an artificial id with the id returned by a call to the publish method. Note that you must wrap the call to publish in a try-catch block because the publish method may throw an exception.
// Invoke remote web service to publish page. try { String publishedId = publish(page); } catch (Exception e) { logger.error(e); throw new RuntimeException(e); }
Note that in this example code we do not handle communication failures or errors internal to the web service. In a real application, additional work would be needed to handle these failures. Use the manager application to restart the wiki application. Then verify that all three applications -- website, publisher and wiki -- function as expected. Open three different browser windows and point them to the following three pages. http://localhost:8080/wiki/view/hello https://localhost:8443/publisher/list-news-items http://localhost:8080/website/home Click the publish operation on the hello wiki page. Refresh the list news items page to see the hello page appear in the list. Refresh the website page to see the new news item appear there as well.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. 47.1 Invocation of the Publish Service from the Wiki Application 197
Java Web Programming with Eclipse Java Web Programming with Eclipse contents Last modified April 02, 2009 02:51 pm
198
Create a new class in the publisher.ws package called UnpublishNewsItemService with the contents of the folliowing listing.
package publisher.ws; import java.io.IOException; import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger; import publisher.data.NewsItem; import publisher.data.NewsItemDAO; public class UnpublishNewsItemService extends HttpServlet { private Logger logger = Logger.getLogger(this.getClass()); protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.debug("doGet()"); String id = req.getParameter("id"); NewsItemDAO newsItemDAO = new NewsItemDAO(); NewsItem newsItem = newsItemDAO.find(new Long(id)); if (newsItem != null) { newsItemDAO.delete(newsItem); } } }
In the doGet method we obtain the id through a call to the getParameter method of the HttpServletRequest object, which is passed in as an argument to the doGet method. After obtaining the id, we perform two interactions with the news item DAO: we call find to obtain an instance of the NewsItem class that represents the news item we wish to delete, then we call the delete method of the news item DAO to delete the news item from the database. Note that we only call delete on the news item DAO if the news item was actually found 48 Web Services (continued) 199
Java Web Programming with Eclipse because it is possible that another user has already deleted this news item from the database. If we had designed the delete method of the news item DAO to take a news item id rather than an instance of the news item class, we would have been able to make a single call into the news item DAO rather than the 2 calls given in the above code. Two different people are likely to differ on their preferences for the form that the delete method takes. It may be that one form is better than the other. However, a more important issue is consistency in the DAOs; the code is easier to read and maintain when the delete methods of all DAOs follow the same pattern. The following XML fragment should be used to the configure the newly created unpublish news item service.
<servlet> <servlet-name>unpublish-service</servlet-name> <servlet-class>publisher.ws.UnpublishNewsItemService</servlet-class> </servlet> <servlet-mapping> <servlet-name>unpublish-service</servlet-name> <url-pattern>/unpublish</url-pattern> </servlet-mapping>
Recall that the security filter in the publisher application only allows unauthenticated requests for the login page and the news feed. We need to modify this filter in order to permit unauthenticated requests for servlet paths equals to /unpublish. You can do this by adding the following code just after the code that checks for a match with /publish.
if (servletPath.equals("/unpublish")) { chain.doFilter(req, resp); return; }
Now, we need to modify the wiki application in order to invoke the unpublish web service when the user issues the command to unpublish a given wiki page. We prepared for this moment by defining a method stub (and unimplemented method) called unpublish in the unpublish page servlet. The following code provides the implementation of the unpublish method; add this code to the unpublish page servlet of the wiki application.
private void unpublish(Page page) throws IOException { logger.debug("unpublish()"); // Construct HTTP headers. String requestLine = "GET /publisher/unpublish?id=" + page.getPublishedId() + " HTTP/1.1\r\n"; String hostHeader = "Host: localhost\r\n"; String connectionHeader = "Connection: close\r\n"; // Send HTTP headers. Socket socket = new Socket("localhost", 8080); OutputStream os = socket.getOutputStream(); os.write(requestLine.getBytes("US-ASCII")); os.write(hostHeader.getBytes("US-ASCII")); os.write(connectionHeader.getBytes("US-ASCII")); os.write("\r\n".getBytes("US-ASCII"));
200
Organize imports and select the following classes from the choices presented to you. java.io.InputStream java.io.OuputStream The page object passed into the unpublish method represents the page that the client wishes to remove from the news feed. The only piece of information in this page object that we need is the news item id. This is what we need to send to the publisher application's unpublish service. The following code shows how we construct the HTTP headers that comprise the HTTP request message that we will send to the publisher application.
// Construct HTTP headers. String requestLine = "GET /publisher/unpublish?id=" + page.getPublishedId() + " HTTP/1.1\r\n"; String hostHeader = "Host: localhost\r\n"; String connectionHeader = "Connection: close\r\n";
The request line is the first line in an HTTP request message. It is comprised of 3 tokens: the HTTP method (GET in this case), the resource being requested (/publisher/unpublish?id="3" for example), and the protocol version number (HTTP/1.1). The request line is where we use the news item id; this id is embedded in the resource token as the value of the id parameter. The host header is a required in version 1.1 of HTTP, so we include this, although in our situation it has no effect other than to create a syntactically valid request message. We include the connection close header so that the web service closes the TCP connection immediately after servicing the request. If we don't do this, the JDOM parser blocks on the input stream until the TCP connection times out. Therefore, we want the server to close the connection quickly, so that processing of the user request in the wiki application completes without delay. After constructing the header strings we send them by making a socket connection with the server and writing the headers into the socket's output stream.
// Send HTTP headers. Socket socket = new Socket("localhost", 8080); OutputStream os = socket.getOutputStream(); os.write(requestLine.getBytes("US-ASCII")); os.write(hostHeader.getBytes("US-ASCII")); os.write(connectionHeader.getBytes("US-ASCII"));
201
Unlike the XML documents that we send in the UTF-8 character encoding, we send the HTTP headers using the US-ASCII character encoding because it satisfies the HTTP protocol. All HTTP header lines are terminated by a carriage return and line feed sequence and the header section of HTTP messages is always terminated by a blank line. Therefore, the last header line we send is the string \r\n. After writing the headers, we flush the output stream to insure that the written bytes are pushed through any buffers and sent into the network. The unpublish service is an example of one-way messaging because the client (wiki application) only sends a message to the service (publisher application) and does not read a response. However, the web service is implemented on top of HTTP, which is a request/response protocol. Therefore, the service will return an HTTP response message to the client. Rather than close the connection abruptly (and possibly generating an exception on the service end), we adhere to the HTTP protocol and read the HTTP response returned by the service.
// Read HTTP response. InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (true) { String headerLine = br.readLine(); if (headerLine.length() == 0) break; }
The implementation of the unpublish method presented in this section does not handle abnormal events. One possible abnormal event is for an error to occur in the service. In this case, the service may return an HTTP error code, rather than a success code. In a more developed implementation, the HTTP response would be examined to see if such an error is reported from the service. In this situation, the wiki application may report the error to the user or handle it in some other way, such as to queue the unpublish request for a later attempt. An alternative to reporting errors in this way is to use 2-way messaging where the service returns a status code that reports a success or failure of the requested operation. Test that the modifications you have just made are correct. To do this, use the manager application to stop and start the publisher application and to restart the wiki application. Open three different browser windows to point at the following three pages. http://localhost:8080/wiki/view/hello https://localhost:8443/publisher/list-news-items http://localhost:8080/website/home Click the unpublish operation on the hello wiki page. Refresh the list news items page to see the hello page disappear in the list. Refresh the website page to see the new news item disappear there as well.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified April 02, 2009 03:50 pm
202
203
Java Web Programming with Eclipse Notice that the canonical name is specified within the distinguished name (dname) parameter. To give an example of how the CN attribute is used by clients, consider the following. The client initiates a secure connection with a host with IP address that the DNS system returned for the domain name cnn.com. Initiating a secure connection means the client starts an SSL handshake procedure in which the server sends its certificate to the client. Suppose that the certificate presented to the server contained a CN value of csusb.edu. In this case, the client's secure socket subsystem rejects the connection because the CN value does not match with the host with which it is trying to connect. One way this could happen is if an attacker took control of the DNS server that the client uses to resolve domain names. We set the CN value to localhost because in our development environment, the client will connect to another process running on the same computer.
You may need to try different forms of the above script to make it work on your system. For this purpose, it's convenient to place the command in a file, and run the file from the terminal window. For Windows, you could call the file extract_publisher_cert.bat, and for Linux/Mac, you can call it extract_publisher_cert.sh. I used the following to make the script run correctly on my system.
"C:\Program Files\Java\jre1.6.0_07\bin\keytool" ^ -export ^ -rfc ^ -file publisher.cert ^ -alias tomcat ^ -storetype JKS ^ -storepass changeit ^ -keypass changeit ^ -keystore "C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf\keystore"
On successful completion of the command, it will report that it created the file publisher.cert. Check to see that this file exists in the wiki project folder in your Eclipse workspace. The next step is to create a truststore that the wiki application will use for its secure connections. A truststore is a collection of trusted certificates. Run the following command from within the wiki project folder in your Eclipse workspace. If you are running under Linux or Mac, remember to replace ^ with \ for line continuation.
keytool -import ^ -noprompt ^ -alias tomcat ^ -file publisher.cert ^ -storetype JKS ^ -keypass changeit ^ -storepass changeit ^
204
Upon successful completion of the above command, a trust store file will be created in web/WEB-INF, which contains the certificate with the public key used by tomcat to establish TLS/SSL connections.
These elements tell the Web container which URLs to apply the security restriction. Add the following two lines to the contextInitialized2 method of the init class within the wiki application.
String trustStorePath = servletContext.getRealPath("/WEB-INF/truststore"); System.setProperty("javax.net.ssl.trustStore", trustStorePath);
In the wiki application, locate the following line inside the publish page servlet.
Socket socket = new Socket("localhost", 8080);
Perform the same replacement in the unpublish page servlet. Start and stop the publisher and wiki applications, and verify that you can still publish and unpublish wiki pages.
205
Java Web Programming with Eclipse Add the following code to the publish news item service. Place the code of the following listing just after the code that extracts the title and link from the request.
// Authenticate client. Element accessKeyElement = item.getChild("accessKey"); if (accessKeyElement == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } String accessKey = accessKeyElement.getText(); User user = new UserDAO().findByAccessKey(accessKey); if (user == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; }
Organize imports. Notice that the findByAccessKey method produces an error because it is not yet defined. Do the following instructions in order to learn a new way to conveniently add the findByAccessKey method to the UserDAO class. Place the cursor in the string findByAccessKey. Hold down the control key and press 1. From the list choose Create method findByAccessKey(String) in type UserDAO. Notice that the UserDAO file opens in the editor window and that a skeleton implementation of the findByAccessKey method is inserted in to the file. Replace the auto-generated contents of findByAccessKey with the contents of the following listing.
ResultSet rs = null; PreparedStatement statement = null; Connection connection = null; try { connection = getConnection(); String sql = "select * from user where accesskey=?"; statement = connection.prepareStatement(sql); statement.setString(1, accessKey); rs = statement.executeQuery(); if (!rs.next()) { return null; } return read(rs); } catch (SQLException e) { throw new RuntimeException(e); } finally { close(rs, statement, connection); }
Modify the read method of UserDAO so that the access key is read from the database and written into the user object that it returns. The read method should look like the contents of the following listing when you are done. 49.1.5 Authenticating Clients 206
Notice that the call to setAccessKey on the user object is marked by Eclipse as a compilation error. To fix this, you need to add an accessKey property to the user class. First, open the User class and declare a private member variable called accessKey of type String. Second, add the following accessor methods to the User class.
public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; }
We need to add an accessKey column to the user table in the database. To do this, modify the createdb.sql script in the publisher project so that the user table creation command looks like the contents of the following listing.
create table user ( id integer primary key, username varchar(255) unique, password varchar(255), accesskey varchar(255) unique );
The accesskey column needs to be unique so that an access key maps to a single user. Also, this declaration results in the construction of an index that makes the select command run efficiently when restricting the select to a given access key value using a select clause. Modify the insertdb.sql script so that an access key is specified for the admin user. The following shows how the access key of 1234 is added to the insert command within insertdb.sql.
insert into user (id, username, password, accesskey) values (4, 'admin', 'D033E22AE348AEB5660FC2140AEC35850C4DA997', '1234');
Run the all target of the ant build file so that tables are dropped, re-created and populated with sample data. Now, we need to modify the unpublish service, so that it also checks for the access key. Add the following code to the doGet method of UnpublishNewsItemService. Place the code of the following listing before the code that looks up the news item to delete.
207
Don't forget to organize imports. Because we haven't modified the client in any way, client attempts to publish a news items should fail, since it is not currently programmed to send the access key.
49.1.6 Test
Stop and then start the publisher and wiki applications. Then try to publish a wiki page and verify that the operation fails and that the server reports a JDOMParseException as shown in the following figure.
49.1.6 Test
208
Actually, the publisher web service is returning a failure code through HTTP with the following line:
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
The doPost method of the PublishPageServlet does not check for failure codes; it simply assumes that the request succeeded and then tries to parse the body of the response as an XML document with a single id element. Therefore, the wiki application reports a parse error, rather than a more useful error message. To fix this problem, read the HTTP status line separately from the request headers, and then after reading through the headers, check to see if the server returned a success code. The following lines of code show how this can be done in the publish method of the PublishPageServlet in the wiki application. The while(true) loop in the following snippet is already in the publish method; you need to add the line that reads the status line before this loop, and then add the code that checks for success after the loop.
// Read the HTTP status line (the first line of the HTTP headers in a response). String statusLine = br.readLine(); // Read through the header lines. while (true) { String line = br.readLine();
49.1.6 Test
209
Now, restart the wiki application. Try to publish a wiki page and observe the more informative error message that is reported. The following figure shows the modified error message by updating the publish method.
Now, modify the publish method of PublishPageServlet so that the access key is sent with each request. Add the following two lines in the same place that we create the title and link elements.
Element accessKeyElement = new Element("accessKey"); accessKeyElement.addContent("1234");
Add the following line to the place in the code where we add titleElement and linkElement to the root element.
49.1.6 Test
210
At this point, the wiki application is sending the access key with publish requests. We still need to have the wiki application send the access key with unpublish requests as well. To do this, modify the line in the unpublish page servlet that constructs the url request. The new line should look as follows.
String requestLine = "GET /publisher/unpublish?id=" + page.getPublishedId() + "&accessKey=1234 HTTP/1.1\r\n";
Restart the wiki application and try to publish and unpublish wiki pages. The applications should work correctly at this point.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 24, 2009 03:37 pm
49.1.6 Test
211
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified January 18, 2009 03:13 pm
212
51 Conclusion
51.1 Overview
This book presented basic techniques of object-oriented design in Java web applications. This will help students to better understand object-oriented designs when they need to deal with them, and will also help the student to begin using object-oriented design in their own software creations. To improve your understanding of this area, you may want to study articles and books that cover design patterns. This book adheres to the standard separation of application logic into model, view and controller that is found in most Java web applications, not to mention other language contexts, such as PHP and Ruby on Rails. The techinques are build on top of Servlets and JSPs, which is the starting point for more sophisticated approaches. After understanding the basic approach presented in this book, the student should be able to master MVC frameworks, such as Struts or Springframework, that are built on top of servlet and JSP. The use of the DAO design pattern to hide the database and present a persistence service to the application has prepared you to begin a study of object relational mapping frameworks, such as Hibernate and Enterpise Java Beans, and understand how these are integrated into the web application. Additional study should be devoted to application security. Additional reading and study should be devoted to database topics, including transaction processing, crash recovery, and distributed databases. Although not mainstream, the student might look into object-oriented databases as an alternative to relational databases. This book did not cover methods to scale web applications to handle loads that exceed the capacity of a single server. Because this is a typical situation in commercial web sites, the student should investigate techniques for distributing load across multiple servers.
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved. Java Web Programming with Eclipse contents Last modified March 24, 2009 03:34 pm
51 Conclusion
213
52 Contents
Title Page Preface Contents Introduction Java Setup Eclipse Setup The Apache Tomcat Web Container Servlet Basics Web Application Logging Java Server Pages A Simple News Feed Application The MySQL Database Server Database-Driven Web Applications Database Connection Pooling Data Access Objects Item Management Overview Interface Design Page Design System Architecture Home Page List Page View Page Edit Page Create Page Delete Page Exercises Web Application Security Overview Configure HTTPS The Persistent User Class Login Functionalty Security Filter Password Digests Exercises Wiki Application Development Overview Database Creation Persistence Classes View Page Edit Page Publish Page Unpublish Page Exercises Web Services Overview A Web Service to Publish News Items Invocation of the Publish Service from the Wiki Application 52 Contents 214
Java Web Programming with Eclipse The Unpublish Service Security Mechanisms Exercises Conclusion
Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved.
52 Contents
215
53
Do not show this Hint Again
53
216