Java Web Programming With Eclipse - CSUSB

Transcription

Java Web Programmingwith EclipseDavid Turner, Ph.D.Department of Computer Science and EngineeringCalifornia State University San BernardinoJinsok Chae, Ph.D.Department of Computer Science and EngineeringUniversity of IncheonCopyright c 2009 by David Turner and Jinseok ChaeVersion December 1, 2009

PrefaceThe purpose of the book is to introduce students to web application development in Java with the use of Eclipse. The book assumes a familiarity withHTML and the Java programming language.The book is in cookbook format in that it provides instructions on howto construct solutions to various problems. The intent is to show studentshow to accomplish typical Web development tasks in the Java language. Inlater chapters of the book, detailed instructions are omitted if they duplicateinstructions in an earlier chapter. This assumes the student can recall orrefer back to the previous instructions. Unguided exercises are also providedso that students can apply what they have covered in the main text. Thebook omits many details and explanations. For these, the reader will needto consult online documentation or search the Web for other tutorials andarticles. Each chapter contains a list of references that the reader may finduseful for filling in these missing details.This is an active book in the sense that the reader is expected to carryout the procedures described. The code examples provided in each chapterare not self-contained; they need to be developed by progressing sequentiallythrough the chapters.1

2December 1, 2009

AcknowledgementsThe following people have helped to create this book. Eyob Zellke Patrick O’Conner The students of Winter quarter 2008 of Server Programming at CSUSB3

4December 1, 2009

Contents1 Introduction to Java Web Application Development111.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.3 Computer Languages Used for Web Application Development 121.4 The Servlet API . . . . . . . . . . . . . . . . . . . . . . . . . 131.5 Java 2 Enterprise Edition (J2EE) . . . . . . . . . . . . . . . . 131.6 Java Server Pages (JSP) . . . . . . . . . . . . . . . . . . . . . 141.7 Rich Site Summary (RSS) . . . . . . . . . . . . . . . . . . . . 141.8 Representational State Transfer (REST) . . . . . . . . . . . . 151.9 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.10 Integrated Development Environments . . . . . . . . . . . . . 151.11 Ant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.12 Web Application Architecture . . . . . . . . . . . . . . . . . . 161.13 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.14 Web Application Servers . . . . . . . . . . . . . . . . . . . . . 181.15 Database Servers . . . . . . . . . . . . . . . . . . . . . . . . . 181.16 Development versus Deployment Environments . . . . . . . . 182 Java Setup2.1 Objectives .2.2 Overview .2.3 Installation2.4 Exercises .21212121223 Eclipse Setup3.1 Objectives .3.2 Overview .3.3 Installation3.4 Issues . . .23232324245

63.53.64 e File Types . . . . . . . . . . . . . . . . . . . . . . .Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2425Apache Tomcat Web ContainerObjectives . . . . . . . . . . . . . . . .Overview . . . . . . . . . . . . . . . .Install Tomcat . . . . . . . . . . . . .Test . . . . . . . . . . . . . . . . . . .Issues . . . . . . . . . . . . . . . . . .Configure Firewall . . . . . . . . . . .Manager Application . . . . . . . . . .Tomcat Documentation . . . . . . . .Log Files . . . . . . . . . . . . . . . .Understanding Tomcat Class LoadingDeep Restart of Tomcat . . . . . . . .Exercises . . . . . . . . . . . . . . . .27272728282830313134353636.3939394041454754556 Web Application Logging6.1 Objectives . . . . . . . . . . . . . . . .6.2 Overview . . . . . . . . . . . . . . . .6.3 Add the Log4j Library to the Project6.4 The Log4j Configuration File . . . . .6.5 The Eclipse Build Process . . . . . . .6.6 Modify HomeServlet . . . . . . . . . .6.7 Exercises . . . . . . . . . . . . . . . .57575758596060655 Java Servlets5.1 Objectives . . . . . . . . . . .5.2 Overview . . . . . . . . . . .5.3 Project Creation . . . . . . .5.4 Attaching Source Code to Jar5.5 Deployment Descriptor . . . .5.6 Create Home Servlet . . . . .5.7 Web Application Deployment5.8 Exercises . . . . . . . . . . . . . . . . .Files. . . . . . . . .7 Java Server Pages677.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677.2 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677.3 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67December 1, 2009

77.47.5Create a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71768 A Simple News Feed Application8.1 Objectives . . . . . . . . . . . . .8.2 References . . . . . . . . . . . . .8.3 Overview . . . . . . . . . . . . .8.4 Flow of information for RSS . . .8.5 Install Libraries . . . . . . . . . .8.6 Modify the JSP . . . . . . . . . .8.7 Test . . . . . . . . . . . . . . . .8.8 Create Publisher Project . . . . .8.9 Exercises . . . . . . . . . . . . .9 The9.19.29.39.49.59.69.79.89.99.109.11.89. 89. 89. 90. 90. 91. 92. 94. 97. 100. 101. 10310 Database-Driven Web Applications10.1 Objectives . . . . . . . . . . . . . .10.2 References . . . . . . . . . . . . . .10.3 Overview . . . . . . . . . . . . . .10.4 JDBC Driver Installation . . . . .10.5 Setup Libraries . . . . . . . . . . .10.6 Create a Dynamic News Feed . . .10.7 Test . . . . . . . . . . . . . . . . .10.8 Exercises . . . . . . . . . . . . . .MySQL Database ServerObjectives . . . . . . . . . . . . .References . . . . . . . . . . . . .Overview . . . . . . . . . . . . .Install MySQL . . . . . . . . . .Test . . . . . . . . . . . . . . . .MySQL-Specific Commands . . .Basic SQL Commands . . . . . .Create a Database of News ItemsCreate Ant Build File . . . . . .Run Targets . . . . . . . . . . . .Exercises . . . . . . . . . . . . .7979797980818486868710510510510510610710811111311 Database Connection Pooling11511.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11511.2 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115December 1, 2009

811.311.411.511.611.711.8Overview . . . . . . . . . . . . . . . . . . . . . . . .Configure the DataSource . . . . . . . . . . . . . . .Modify the News Feed Servlet . . . . . . . . . . . . .Create a ServletContextListener to do Initialization .Test . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises . . . . . . . . . . . . . . . . . . . . . . . .11511611711812012012 Data Access Objects12.1 Objectives . . . . . . . . . . .12.2 Overview . . . . . . . . . . .12.3 Create NewsItem Class . . . .12.4 Create DataAccessObject . .12.5 Modify the News Feed Servlet12.6 Test . . . . . . . . . . . . . .12.7 Exercises . . . . . . . . . . .12112112112312413013213213 Item Management13.1 Objectives . . . . . .13.2 Overview . . . . . .13.3 Interface Design . . .13.4 Page Design . . . . .13.5 System Architecture13.6 Home Page . . . . .13.7 List Page . . . . . .13.8 View Page . . . . . .13.9 Edit Page . . . . . .13.10Create Page . . . . .13.11Delete Page . . . . .13.12Exercises . . . . . .133133134136139145149153156160170175180.183. 183. 184. 185. 190. 196. 204. 208. 214.14 Web Application Security14.1 Objectives . . . . . . . . .14.2 Overview . . . . . . . . .14.3 Configuration of HTTPS .14.4 The Persistent User Class14.5 Login Functionality . . . .14.6 Security Filter . . . . . .14.7 Password Digests . . . . .14.8 Exercises . . . . . . . . .December 1, 2009

915 Wiki Application Development15.1 Objectives . . . . . . . . . . . .15.2 Overview . . . . . . . . . . . .15.3 Project Creation . . . . . . . .15.4 Persistence Classes . . . . . . .15.5 View Page . . . . . . . . . . . .15.6 Edit Page . . . . . . . . . . . .15.7 Publish Page . . . . . . . . . .15.8 Unpublish Page . . . . . . . . .15.9 Exercises . . . . . . . . . . . .16 Web Services16.1 Overview . . . . . . . . . . . . . . . . . .16.2 A Web Service to Publish News Items . .16.3 Invocation of the Publish Service from the16.4 The Unpublish Service . . . . . . . . . . .16.5 Security Mechanisms . . . . . . . . . . . .16.6 Exercises . . . . . . . . . . . . . . . . . . . . . .Wiki. . . . . . . . . . . . . . . . . . .Application. . . . . . . . . . . . . . . . . . .215215216218221229236242248253255. 255. 259. 265. 272. 278. 29017 Conclusion29117.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291December 1, 2009

10December 1, 2009

Chapter 1Introduction to Java WebApplication Development1.1Objectives To understand the big picture of web development using Java. To learn about web services and how they will be used in this book.1.2OverviewThe 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 developmentbecame an important discipline following the adoption of the Internet byordinary users. Many businesses now rely heavily on the web for both internal applications and to provide services to customers, and so there aremany employment opportunities open to individuals with web developmentskills.Web sites can be roughly classified as static or dynamic. Static web sitesare those sites that use a web server to provide access to HTML documentsthat are stored in the file system. Dynamic web sites are those sites thatconstruct the content of web pages from data that is stored in a database.The databases on which these dynamic sites are built are typically modifiedas a result of user interaction with site. Thus, users are presented withweb pages that are uniquely generated for them based on their previousinteractions with the site. The trend is for web pages to be generated from11

12databases rather than being read from the file system.1.3Computer Languages Used for Web Application DevelopmentThere are numerous languages and frameworks that are used for web application development. Java is one of the older and more established languagesin which web applications have been developed. This book covers Java-basedweb application development using Servlets and JSP. This book also coversthe news feed protocol RSS version 2.0, and REST-based web services.Java is a strict object-oriented language in which all function calls aremade to either static methods of classes or to non-static methods that areinvoked through class instances. These classes are organized into namespacescalled packages, so that unqualified class names do not need to be globallyunique.An application programming interface (API) is a specification that defines how user code can access system functionality. The Java API refers tothe specification that defines how Java code may access functionality, suchas opening a file in the file system, creating a socket connection with anotherprocess, creating a linked-list of objects, etc. For example, the following linecreates an instance of the Socket class, which can be used to make TCPconnections to other processes.java.net.Socket socket new java.net.Socket("localhost", 8080);The above line of code can be simplified by importing the class java.net.Socketinto the local namespace by adding the following line just after the packagedeclaration of a java source code file.import java.net.Socket;The above import statement allows for the following simplified versionof the socket creation code give above, in which the package prefix qualifiersare dropped from the Socket class.Socket socket new Socket("localhost", 8080);December 1, 2009

131.4The Servlet APIThe Socket class is an example of a class that is part of the core Java API,which is available in all standard Java virtual machine (JVM) environments.However, web applications typically additional functionality that is not partof the core Java API. In particular, conventional web applications need tobe able to access functionality provided through the Servlet API. Implementations of the Servlet API are provided by third parties, such as Apache,IBM, Oracle, etc. In fact, the Servlet API is provided by something calleda web container (or Servlet container), which is defined within an extensive specification called Java 2 Enterprise Edition (J2EE). A web containeris actually a web server that loads and executes Java Servlets to processincoming requests from browsers (or other HTTP clients).1.5Java 2 Enterprise Edition (J2EE)The Java 2 Enterprise Edition is a specification developed by Sun Microsystems with input from other major companies in the industry through amechanism called the Java Community Process (JCP). J2EE describes a setof services that application developers utilize to solve enterprise computingproblems. There are many third party implementations of J2EE, includingboth expensive proprietary implementations, and free open source implementations. The Apache Software Foundation provides a free open sourceimplementation of J2EE web containers, called Tomcat, which is widely usedin the industry for web applications. This book describes the use of Tomcat,and does not discuss other web containers.Tomcat is not a complete implementation of the J2EE standard. Inparticular, it does not provide an Enterprise Java Beans (EJB) container.JBoss is a popular, free, open source implementation of the complete J2EEstandard. The JBoss project itself does not provide an implementation ofthe Web container; instead, it requires that a third party web containerbe plugged in. However, Tomcat is the default Web container that comespackaged and pre-configured with JBoss. A popular alternative to Tomcatis Resin and a popular non-free alternative to JBoss is IBM’s WebSphere.December 1, 2009

141.6Java Server Pages (JSP)The use of Java Server Pages (JSP) is covered in this book. JSP is a notationthat is added to HTML files, so that per-request functionality can be addedto otherwise statically-defined HTML.It is possible to place all program functionality into JSP files. However,this practice is widely frowned against, because it leads to code that isdifficult to maintain after a project grows in size. There are several reasonsfor this. First, JSP files are compiled at runtime by the web container,so that syntax errors are detected at runtime. By placing this code intoServlets, syntax errors are detected at compile time, which allows syntaxerrors to be caught and fixed at an earlier point in time. Second, JSP filescan not make use of inheritance, so that projects solely written in JSP lookmore like functional programs rather than object-oriented programs, andthus do not make use of the benefits provided by object-oriented design.One can move away from pure JSP designs in two degrees: the javabeans approach, and the servlet approach. The Java beans approach movesdatabase access and other logic into Java beans, which are then invokedfrom the JSP. The Servlet approach also moves database access and otherlogic into Java beans, but also moves controller logic into Java Servlets, andinvokes most of the Java bean functionality from the servlets. This bookillustrates the Servlet approach.1.7Rich Site Summary (RSS)Rich Site Summary (RSS) is an XML-based format for syndicating content.In this book, we show how RSS can be added to a Java-based Web application from both the client side and from the server side. Rather than developall the needed code from scratch, we utilize functionality provided by twodifferent open source projects: JDOM and Informa. JDOM is a library thatsimplifies the processing of XML documents, and Informa is a library thatsimplifies the parsing of RSS documents. These libraries come in the formof jar files, which are zip files containing the byte code that comprise Javaclass and interface definitions. To access the functionality provided by theselibraries, the jar files must be placed in what is called the classpath. Theclasspath is basically a list of folders and jar files that the Java classloadersearches to find definitions of Java classes. When the jar file of a library ispresent in the classpath, then its API becomes visible to application code.There is a tool, called javadoc, that is used to generated API documenDecember 1, 2009

15tation from code and the comments embedded within it. This generateddocumentation is in the form of HTML pages, and is thus viewed withina browser. It is important to become familiar with javadoc-generated APIdocumentation, because it is the standard means to document Java APIs.1.8Representational State Transfer (REST)Representational State Transfer (REST) is formally an architectural stylefor building distributed software applications, that is, software systems thatrun on separate computers and that communicate with each other over anetwork. However, the term is informally used to represent an approachto building Web services in which message data is placed in XML documents and transported using HTTP. In this second meaning, REST is analternative to the more complex form of Web services based on SOAP andWSDL.1.9Web ServicesSoftware systems that provide programmatic interfaces to other systems (asopposed to browsers operated by human users) are similar to web applications in the sense that they rely on the Internet and usually rely on theHTTP protocol. These applications are referred to as web services. Thisbook provides an introduction to REST-based web services.1.10Integrated Development EnvironmentsWhen developing software, programmers tend to rely on integrated development environments (IDEs). An IDE provides important time-saving functionality, such as syntax checking, code assist and re-factoring. With syntaxchecking, the IDE will alert you if you have typed a command incorrectly.The term code assist refers to the ability of the IDE to suggest completionsto a piece of code that you are working on. For example, if a locally scopedvariable is named maximumLikelihoodEstimator and you wish to use thisvariable in an expression that you are typing, then you can invoke the codeassist function to obtain a list of identifiers to choose from. As you type incharacters, the list is narrowed to match only those identifiers that matchwith the characters you have so far entered. Re-factoring functionality allows you to change the name of an identifier in one part of the code, andhave the IDE change the name as it occurs throughout the entire code base.December 1, 2009

16These and other time saving functions make IDEs highly useful tools fordevelopers.1.11AntAnt is the Java version of the make utility that is commonly used to buildprograms written in C or C . Without an IDE such as Eclipse, a Javaprogrammer would normally write ant build scripts to perform repetitivetasks, such as compiling and packaging compiled code into archives (jarfiles). With an IDE such as Eclipse, programmers can invoke commonlyused operations such as building through the GUI of the IDE. However,there will always be a need to develop scripts in non-trivial projects toautomate repetitive tasks. For this reason, this book covers the use of antfor running database regeneration scripts and for generating various objectsneeded for application security.Ant is built into Eclipse, so the user can run ant build scripts throughthe 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 oneor more targets, each of which perform some job. Each target is comprisedof any number of tasks, which comprise the atomic actions that a user canspecify.Ant is a free, open source project maintained by the Apache SoftwareFoundation. The ant build system is well documented, and there are numerous tutorials and articles on its use. This book employs ant in a simpleway, so that students can become familiar with its use and the syntax of anant build file.1.12Web Application ArchitectureThere are many different ways to design Java-based web applications. Thisbook presents a particular design. In this book, we show how to implementa web application that follows what is popularly called the model-viewcontroller (MVC) architecture. The MVC approach attempts to separatecode into three areas of concern: persistence and business logic (model),user interface generation (view), and user input (controller). In java applications, MVC is usually implemented by generating HTML from JavaServer Page (JSP) scripts, handling incoming requests with servlets. Persistence of data is done through data access objects (DAOs) or EnterpriseJava Beans (EJBs), and business logic is placed inside servlets, EJBs orDecember 1, 2009

17other classes. In this book, we do not look at EJBs; instead, we use DAOsto provide persistence services, and place business logic within servlets andother classes.Data access objects (DAOs) are used to provide persistence functionalityfor objects that can not be stored in main memory indefinitely. For example,the application may have a class called User that is used to represent usersof the system. The User object will contain username, password, emailand other attributes needed by the application. This information obviouslyshould survive the restart of the system, and so must be preserved in thenon-volatile memory such as a hard disk drive. Objects that are instancesof such classes as User are termed persistent objects. Although the state ofpersistent objects can be stored directly in the file system, they are usuallystored in a database.Some databases are object-oriented, which makes storing persistent objects in them straightforward. However, object-oriented databases havenot gained wide acceptance; instead, developers use relational databasesin which data is stored in tables of rows and columns. The transferenceof data between objects in memory and tables in the database is not astraightforward process. Consequently, a lot of code needs to be written toimplement this functionality. In fact, there are frameworks (such as Hibernate or iBatis) that can be used to simplify the addition of this capability toan application. Use of these frameworks is not covered in this book. Instead,we will develop our own persistence mechanism by placing such code withinour data access objects.There is an alternative to using persistent objects, which is to operatedirectly on the data within the database without encapsulating it withinobjects. This approach removes a lot of complexity from the code for smallprojects, however, larger projects benefit from the use of persistent objectsbecause it simplifies the expression of the application’s business logic. Thisbook focuses on an approach to web application design that is based onpersistent objects.1.13SecurityIn the Java Web development world, there are several ways to implementsecurity features in an application. This book uses a simple approach toauthentication and authorization. A unified process of validating user inputis also presented.December 1, 2009

181.14Web Application ServersJava Web development is usually done using Servlets and JSP. Both Servletsand JSP are standard APIs that were developed through the Java Community Process, which is a mechanism by which the Java language is subject toreview and modification by the community. As a result of being developedas standards, there are many competing implementations of what are calledServlet/JSP containers. Some implementations are proprietary and licensedfor a fee, such as IBM WebSphere and Oracle Application Server. Othersare free, open source, such as Tomcat and Resin. In this book, we use theTomcat web container. The code that is developed in this book, will generally run unmodified in any Web container. However, certain details relatedto deploying the application in a particular web container are not subjectto the standard, and thus vary between implementations.1.15Database ServersA database server is an essential tool to Web developers, no matter whichlanguage, framework or operating system they use. Typically, web developers use relational database servers, although alternatives exist, such asobject-oriented database servers. Currently, the most widely used databaseserver in industry is probably Oracle. However, there are some good qualityalternatives to Oracle, such as MySQL and PostgreSQL. In this book, weuse the MySQL database server, because it is the most widely used free,open source database server.1.16Development versus Deployment EnvironmentsOne important concept that students are not usually aware of is the distinction between a development environment and a production environment.The book describes how to set up and use a development environment.Specifically, this book details the steps needed to set up a Windows machine to be used for development of Web applications. However, the bookdoes not cover the set up of an environment in which to run Web applicationsto be used in a business context.Although it is possible to use Windows as the operating system in a production environment, the Linux operating system is perhaps a more commonplatform for production servers. Details of installation and configuration ofa production environment for Java web applications is not covered. Also notDecember 1, 2009

19covered are methods used to distribute load across multiple servers, whichis a common necessity in production environments.December 1, 2009

20December 1, 2009

Chapter 2Java Setup2.1Objectives To install Java in your development environment.2.2OverviewAll Java code runs inside a Java Virtual machine (JVM). The system thatprovides 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 theJava Development Kit (JDK), which contains both a runtime environmentand 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 withinit, but also provides additional libraries, additional tools, and a J2EE Application Server. For the purposes of this book, we only need the J2SEJDK.2.3InstallationIf Java is not already installed on your system, then you should go to Go toSun Developer Network and locate the download page for the most recentrelease of the Java Standard Edition (SE) Software Development Kit; atthe time of this writing, this was titled Java SE Development Kit (JDK) 6Update 11. Download and install this package.21

22Optionally, you can install the documentation titled Java SE 6 Documentation. Alternatively, you can simply access Sun’s online version of theJDK 6 Documentation. The most important part of the documentation isthe Java Platform API Specification.2.4Exercises(1) Test InstallationTest your installation by running the java command with the version option.To do this, obtain a command prompt and execute the following.java -versionNotesLater procedures in the book may require creating an environmental variable called JAVA HOME. Also, modifying the PATH variable may also beneeded.December 1, 2009

Chapter 3Eclipse Setup3.1Objectives To install Eclipse in your development environment. Learn how to modify the default behavior of Eclipse by associatingnew file types with the text editor.3.2OverviewEclipse is a tool for building software projects. Such a tool is also referredto as an integrated development environment, or simply IDE.Eclipse is similar to Microsoft Visual Studio, except that it is free andopen 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. Thedevelopment of eclipse is now managed by the Eclipse Foundation, which isa non-profit organization.Eclipse can be easily extended by any programmer. Eclipse comes withextensiv

Java is one of the older and more established languages in which web applications have been developed. This book covers Java-based web application development using Servlets and JSP. This book also covers the news feed protocol RSS version 2.0, and REST-based web services. Java is a strict