You have now extended Eclipse with a J2EE servlet containerand are ready to create your first Java Web application development project... The wizard opens the J2EEperspective for you so
Trang 1Iteration 1: J2EE Web Applications 49
3 Click the Next button to display the Tomcat Server page Click the Browsebutton to select the directory where you installed Tomcat (see the GettingTomcat sidebar), for example,
E:\jakarta-tomcat-5.0.28
The Tomcat installation directory field should now show the selecteddirectory (see Figure 3.4)
Figure 3.4 Tomcat Server
4 The JRE field is initialized to the Workbench default JRE, which is the JVMyou used to launch Eclipse
JDK Required for JSP Development
Part of the server runtime environment setup process involves specifying the JRE touse for launching Tomcat Be sure to specify a full JDK instead of just a JRE becauseyou’ll be doing JSP development If you do not currently have a JDK defined to Eclipse,add the one you previously installed (see the Getting a JDK sidebar) JSP developmentrequires a Java compiler, which is included in the JDK but not the JRE JSP compilationwill fail if you specify a JRE Note that you can precompile your JSPs in order to use aJRE in your production server environment
Trang 2Click the Installed JREs button to open the Installed JREs wizard This wizardlets you define additional JREs to Eclipse Click the Add button and selectthe directory where you installed the JDK (see the Getting a JDK sidebar),for example,
E:\ibm-java2-142
The JDK is added to the Installed JREs page Select its checkbox to make itthe default JRE (see Figure 3.5), and click the OK button to return to theTomcat Serverpage
Figure 3.5 Installed JREs
5 Select the JDK from the drop-down list of the JRE field (see Figure 3.4).When WTP launches Tomcat later, it will use the specified JDK Click theFinishbutton to complete the definition
Tomcat is now listed on the Installed Server Runtime Environments page (seeFigure 3.6) You have now extended Eclipse with a J2EE servlet containerand are ready to create your first Java Web application development project
Trang 3Create a Dynamic Web Project
We assume you are familiar with the Eclipse concepts of workspace, project, and
builder Recall that an Eclipse workspace contains a set of projects You typically
put projects that are related to each other in the same workspace For example, inJ2EE development, you would put related Web, EJB, and utility projects in thesame workspace Each project has a set of builders associated with it Builders arewhat give the project its intelligence Builders know how to process the artifacts in
a project The most common example of a builder is the Eclipse incremental Javacompiler, which knows how to compile your Java source files into class files.WTP provides builders for Java Web applications These builders know, forexample, how to package the artifacts in J2EE modules so that they can bedeployed to J2EE application servers
In general, a J2EE application will contain several modules For example, youmight want to use a Web module for the presentation logic and an EJB modulefor the business logic Here you’ll just develop a Web module Do the following toadd a Web module to your workspace:
Figure 3.6 Installed Server Runtime Environments with Tomcat Added
Trang 41 To begin development, create a new dynamic Web project by invoking theFile䉴 New䉴 Projectmenu command to open the New Project wizard.Select Web 䉴Dynamic Web Projectas the project type (see Figure 3.7).
Figure 3.7 New Project
2 Click the Next button The Dynamic Web Project page is displayed (seeFigure 3.8) Enter Web1in the Project Name field Note that Apache Tomcat
is selected as the Target Runtime since it is the only server runtime ment you have defined The Configurations field lets you select a predefined
environ-configuration of project facets Leave the setting as <custom> for now You
can also ignore the checkbox to add the Web module to an EAR projectsince Tomcat is just a servlet container and doesn’t support EARs
3 Click the Next button to advance to the Project Facets page (see Figure 3.9) A
facet is part of the runtime configuration of a project, such as the version of
Java or J2EE Facets will be discussed in more detail in Chapter 6 For now,simply accept the selections
4 Click the Next button to advance to the Web Module page (see Figure 3.10).You can change some of the project settings here For example, the ContextRoot of the Web application defaults to its project name, Web1.Accept thedefaults for now
Trang 5Iteration 1: J2EE Web Applications 53
Figure 3.8 Dynamic Web Project
Figure 3.9 Project Facets
Trang 65 Click the Finish button to create the Web project Since this is the firsttime you have created a Web project, you are prompted to accept theJ2EE license from Sun (see Figure 3.11) WTP will next attempt to down-load the J2EE schemas from the Sun Web site, so you must accept thelicense before WTP proceeds Products built on top of WTP may haveobtained the right to redistribute the J2EE schemas, in which case youwon’t see this dialog.
6 Click the I Agree button to accept the license Note that if you
do not accept the license, then WTP will be unable to validate the
J2EE XML artifacts, such as the deployment descriptors (e.g., web.xml),you create
WTP has a special J2EE perspective and will attempt to switch to
it when you create any J2EE project, such as a dynamic Web project
or an EJB project One of the user interface design guidelines of Eclipse is
to not switch perspectives without asking the user if they want to
You are therefore prompted to switch perspectives (see Figure 3.12)
Figure 3.10 Web Module
Trang 77 Click the Yes button to agree to the switch The wizard opens the J2EEperspective for you so you can see the logical structure of your modules.The J2EE Project Explorer view (see Figure 3.13) now shows the projectstructure after Web1has been created Note that the wizard created somefolders and files under the Web1module These items are defined by theJ2EE specification For example, the WebContentfolder is the root of theWeb application and is where the normal Web content, such as HTML
Figure 3.12 Open Associated Perspective
Figure 3.11 License Agreement
Trang 8Figure 3.13 Project Explorer View
Create and Edit a JSP
Add a JSP file to your project as follows:
1 Add a new JSP file to the WebContentfolder of Web1as follows In theProject Explorerview, expand Web1,right click on WebContent,and invokethe New 䉴JSPcommand to open the New JavaServer Page wizard Give thenew file the name hello-world.jsp The wizard lets you pick a templatefor the new JSP Select the template for JSP with HTML markup, and clickthe Finish button
2 The wizard creates the JSP file with the content filled in from the templateand opens it in the JSP editor The JSP editor provides full content assist onHTML tags, JSP tags, and Java code scriptlets Edit the JSP to say “Hello,world” using HTML tags (see Figure 3.14) The Web application is nowready to run
pages, JSPs, and images, go The WebContentfolder contains a specialfolder named WEB-INF, which contains items that are not accessible by aWeb browser The WEB-INFfolder is where compiled Java code goes Italso contains a special file, web.xml, which is the J2EE Web deploymentdescriptor; more on that later (see Chapter 7) Now you are ready to start creating the content of the Web application
Trang 9Run the JSP on the Server
The Eclipse Java Development Tools (JDT) lets you run a Java main program(i.e., a Java class that has a standard mainmethod) by selecting its source file andinvoking the Run As䉴 Java Applicationcommand WTP extends the Run As com-mand to Web artifacts such as HTML and JSP files Simply select the file andinvoke the Run As䉴 Run on Servercommand from the context menu In WTP, aserver runtime environment plays the role that a Java runtime environment plays
in JDT Another difference between JDT and WTP is that in JDT, the input andoutput of the Java application is displayed in the Console view, but in WTP, theuser interface of a Web application is hosted in a Web browser
Run your JSP file as follows:
1 Select hello-world jspand invoke the Run As䉴 Run on Servercommandfrom the context menu Since this is the first time you have tried to run anyartifact from the Web1project, WTP will prompt you to define a new server(see Figure 3.15) WTP defaults the server runtime environment to ApacheTomcat, which you previously associated with the project However, in
Figure 3.14 JSP Editor
Trang 10WTP a server consists of both a server runtime environment and
configura-tion informaconfigura-tion such as the port numbers to use and the set of projects todeploy or publish on it Note that a project may be deployed on severalservers, which is handy when you are testing a Web application for porta-bility to different vendors
Figure 3.15 Define a New Server
2 Click the Next button to advance to the Add and Remove Projects page(see Figure 3.16)
3 Click the Finish button to confirm that you want WTP to add the Web1module to the server configuration WTP then starts the server and opens
a Web browser with the Uniform Resource Locator (URL) of the JSP file(see Figure 3.17)
Trang 11Iteration 1: J2EE Web Applications 59
Figure 3.16 Add and Remove Projects
Figure 3.17 Web Browser—hello-world.jsp
Trang 12Summary of Iteration 1
In this iteration you added Tomcat to Eclipse as a server runtime environment, ated a dynamic Web project, added a JSP file to it, and ran the project on Tomcat.Congratulations! You have just created your first Web application withWTP You’re now ready to add some Java code and do a little debugging
cre-Iteration 2: Servlets and Scriptlets
The Web application you have created so far is rather boring since it is static.There is no way to interact with this application You could have achieved thesame behavior using an HTML page To liven things up, you will add some Javacode You’ll add a Java scriptlet to your JSP This scriptlet will look for a queryparameter in the request and display its value You’ll also create another JSP toprompt the user to enter this parameter, and you’ll add a Java servlet to controlthe application flow between these JSPs In this process, you’ll use the debugger
to step through both the JSP and the servlet code You’ll perform the followingdevelopment tasks in this iteration:
1 Add a Java Scriptlet to a JSP
2 Debug a JSP
3 Create a Servlet
4 Debug a Servlet
Refer to Chapter 7 for more detail
Add a Java Scriptlet to a JSP
The simplest way to add dynamic behavior to a JSP is to insert a Java scriptlet.
A Java scriptlet is a block of Java code that gets executed when the JSP isrequested Java scriptlets are placed inside of <% and %> delimiters Within ascriptlet, the Java code has access to several predefined variables For example,the HTTP request is represented by a request variable The scriptlet can re-trieve the HTTP query parameters from the requestvariable
WTP Launches Tomcat in a New JVM Process
WTP starts Tomcat in a new process using the JVM that you specified when youdefined its server runtime environment If you have another Tomcat process currentlyrunning, you will be unable to start Tomcat from WTP unless you use a different set
of port numbers (see the Ports Already in Use sidebar earlier in this chapter)
Trang 13Iteration 2: Servlets and Scriptlets 61
You’ll now make your JSP display the name of the user that is passed in onthe request URL as a query parameter Query parameters are specified after the
“?” in the URL For example, to greet Alice, you request the JSP using the URLhttp://localhost:8080/Web1/hello-world.jsp?user=Alice
Do the following to add dynamic behavior to your JSP:
1 Edit the hello-world.jspfile in the JSP editor and add the scriptlets (see Example 3.1) Here, the Java scriptlet gets the value of the userqueryparameter from the request, checks if it’s null, and creates a personstringthat is then displayed on the page
Example 3.1 Listing of hello-world.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
String user = request.getParameter("user");
if (user != null) person = user;
You now have some executable code to try out However, rather than simply run
it, you’ll debug it Do the following to debug your JSP:
1 Setting a breakpoint in a JSP file is just like setting one in a Java file.Simply double-click in the left-hand margin on the line where you wantexecution to halt Set a breakpoint now in hello-world.jspon the follow-ing line of the scriptlet:
String user = request.getParameter("user");
Trang 14Figure 3.18 Select Tasks
2 Select hello-world.jsp and invoke the Debug As 䉴 Debug on Servercommand from the context menu Since you have modified the JSP, WTP will prompt you to update the Web application (see Figure 3.18)
3 Check the box to update the context root of Web1and click the Finish ton WTP will update Web1and restart the server in debug mode Since theserver is currently not in debug mode, WTP will prompt you to confirmthe mode change (see Figure 3.19)
but-Figure 3.19 Debug On Server
4 Select the Switch mode radio button and click the OK button WTP willrestart the server in debug mode and request the JSP in a Web browser as
Trang 15Iteration 2: Servlets and Scriptlets 63
before Execution will now halt at the breakpoint and WTP will attempt
to open the Debug perspective Since this is a perspective switch, WTPwill prompt you to confirm the switch Accept the perspective switchand view the JSP halted at the breakpoint Use the Debug perspective asusual to explore the halted state Click the Resume button to continueexecution
5 To debug the query parameter handling, go to the Web browser, appendthe query string
?user=Alice
to the end of the URL, and refresh the browser Execution will halt again
at the breakpoint (see Figure 3.20) Click the Step Over button to executethe line of code that assigns the value Aliceto the uservariable Note thatthe Variables view shows the value of the uservariable set correctly
Figure 3.20 Debug Perspective
Trang 16Figure 3.21 Web Browser—hello-world.jsp?user=Alice
6 All of the usual Java debugging functions are available for JSPs Continue
to explore the variables and step through the code Click the Resume ton to complete the processing of the HTTP request (see Figure 3.21).Note that the greeting is now “Welcome to WTP, Alice!”
but-Create a Servlet
The code for a Web application includes business logic, application logic, and tation logic Business logic implements business rules such as how to compute pricesand taxes Application logic implements the flow of control between Web pages.Presentation logic implements how the data is rendered in the Web browser SinceJSPs can contain arbitrary blocks of Java code, it is tempting to put all of the logic inthe JSPs However, when designing a Web application, it is good practice to limit thecode in JSPs to just the presentation logic Application logic should be put in servletsthat invoke Java business objects, get the results, and pass them back to JSPs as pres-entation objects Business logic should be put in Java classes that are independent ofthe presentation and application logic so they can be easily reused and maintained
Trang 17presen-Iteration 2: Servlets and Scriptlets 65
You’ll modify your example to illustrate this design pattern Your example rently consists of a single JSP, hello-world.jsp,which checks for the presence of theuser query parameter and displays its value Users do not normally tack queryparameters on to the end of URLs by hand Instead, users enter parameters intoHTML forms, and then click a submit button to send the parameters to the server forprocessing To implement this servlet design pattern, you’ll add the following files:
cur-❍ login-user.jsp—a JSP that presents an HTML form to the user and sendsthe input to the HelloServletservlet for processing This JSP also displays
an error message if one is present The error message lets HelloServletcommunicate with the user
❍ HelloServlet.java—a servlet that checks for the presence of the userqueryparameter If the query parameter is present and contains a nonempty user
id, the servlet forwards the request on to hello-world.jspfor presentation
to the user Otherwise the servlet generates an error message for the user andforwards the request back to login-user.jsp.
Do the following to implement the servlet design pattern in your project:
1 Begin by creating login-user.jspusing the New JSP wizard Enter its code(see Example 3.2)
Example 3.2 Listing of login-user.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
Object error = request.getAttribute("error");
if (error != null) error_message = error.toString();
%>
<form action="HelloServlet">
<table cellspacing="4">
<tr>
<td>Enter your user name:</td>
<td><input name="user" type="text" size="20"></td>
<td style="color: red"><%= error_message %></td>
Trang 18login-user.jspchecks for the existence of an optional error message and,
if present, displays it on the page Note that the actionattribute of theLoginbutton is set to HelloServlet When the user clicks the Login button,the value of the input field gets sent to HelloServletas the value of theuserquery parameter Your next step is to create the HelloServlet.javaclass that will process the request
2 Create the HelloServlet.javaservlet as follows: Select the Web1projectand invoke the New䉴 Servletcommand from the context menu Thisopens the New Servlet wizard Create the servlet in the srcdirectory of theWeb1project and give it the package name
Trang 19Iteration 2: Servlets and Scriptlets 67
Note that the Generate an annotated servlet class checkbox gives you the option of using XDoclet Uncheck this option for now We’ll discussXDoclet in Chapter 6
3 Although you could finish here, click the Next button to view the nextpage The wizard lets you modify the default servlet name and URL map-ping Accept the default servlet name HelloServletand URL mapping/HelloServlet(see Figure 3.23) The servlet name is used for internalbookkeeping in web.xml.For example, the servlet name links the servletclass with the URL mapping The URL mapping determines how theservlet is invoked This value must match the value you specified in theaction attribute of the HTML form element in login-user.jsp.Althoughyou use the URL mapping /HelloServlet,it is a better practice to use avalue that doesn’t expose the implementation details, such as the fact thatyou are using a servlet In practice, you may change the implementation,
so it is a good idea to minimize the number of URLs that are affected
Figure 3.23 Create Servlet—Deployment Descriptor
4 Click the Finish button The wizard creates the skeleton of the servlet Allyou need to do is fill in the application logic in the body of the doGetmethod Enter the code for the servlet (see Example 3.3)
Trang 20Example 3.3 Listing of HelloServlet.java
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { String url = "/hello-world.jsp";
String user = request.getParameter("user");
if (user == null || user.length() == 0) {
url = "/login-user.jsp";
request.setAttribute("error", "User name must not be empty."); }
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url); dispatcher.forward(request, response);
}
}
Trang 21Iteration 2: Servlets and Scriptlets 69
TheHelloServletclass implements the doGetmethod, which handles HTTPGET requests The purpose of the servlet is to decide which JSP should han-dle the request The servlet computes the URL of the appropriate JSP and for-wards the request to it using the forwardmethod of the RequestDispatcherclass.The servlet grabs the userquery parameter from the request using thegetParametermethod If the userquery parameter is absent, or it is an emptystring, the servlet generates an error message, stores it as an attribute of therequest using the setAttributemethod of the HttpServletRequestclass, andsets the URL to login-user.jsp.If the userquery parameter is present andnon-empty, the servlet sets the URL to hello-world.jsp.
Debug a Servlet
Debugging a servlet is very similar to debugging an ordinary Java class, exceptthat you use the Debug As 䉴Debug on Server command, just as you did for JSPs.You’ll now debug the application control flow Debug the servlet as follows:
1 Set a breakpoint in HelloServlet.javaon the line of the doGetmethodthat contains the code
String user = request.getParameter("user");
2 Select HelloServlet.javain the Project Explorer view and invoke theDebug As 䉴Debug on Servercommand from the context menu This com-mand starts the server in debug mode and opens a Web browser with theURL of the servlet, which in this case is
http://localhost:8080/Web1/HelloServlet
What do I do if I get a 404?
Sometimes when you run or debug a servlet or JSP, you might get a 404 in the Webbrowser This problem is caused by the Web browser requesting the resource beforethe server has fully deployed it WTP detects when resources have changed andrepublishes them to the server However, there may be a time delay as the serverrestarts If you run into a 404, manually restart the server from the Servers view andtry again
3 Step through the code and verify that there is no value set for the userquery parameter The servlet therefore generates an error message and for-wards the request to the login-user.jsp.Click the Resume button in thedebugger to allow execution to proceed login-user.jspis displayed in
Trang 22the Web browser, with the error message prompting the user to enter auser id (see Figure 3.24).
4 Do a little testing now If you click on the Login button, control is passedback to the servlet, which generates the error message again and forwardsthe request back to login-user.jsp.This time enter a user id and clickLogin Now the servlet forwards control to hello-world.jsp.
Summary of Iteration 2
In this iteration you created and debugged a servlet that controlled the tion logic of your Web application For simple Web applications, you can codethis logic manually However, for complex applications, you should considerusing a Web application framework, such as JSF, Struts, or Spring MVC
presenta-In Struts, the control flow logic is externalized into an XML configurationfile so that you can easily modify it Struts also provides a framework for many
Figure 3.24 Web Browser—login-user.jsp
Trang 23common Web application programming tasks, such as parameter passing anderror handling Although Struts enjoys widespread popularity among Java Webapplication developers, it is not part of J2EE The ideas behind Struts have beenstandardized in JSR 127: Java ServerFaces, which is now part of Java EE 5 WTP1.5 includes the JavaServer Faces Tools incubator subproject, which will become
a component of JST in WTP 2.0
Iteration 3: Database Access
Virtually every Web application takes input from users and stores it on theserver Relational databases are by far the most popular technology for storingdata XML promises to become another popular storage format since it is moreconvenient for semi-structured data than relational tables In fact, relationaldatabases are now being updated to store and query XML data XML data can
be queried using SQL extensions, XPath, XSLT, and the new XML query guage, XQuery We’ll discuss XML more later in Chapters 7 and 10, but for nowwe’ll focus on relational databases
lan-You’ll extend your Web application by adding some very simple databaseaccess Rather than greet users by their user id, you’ll update your application togreet users by their full names You’ll create a relational database to store a table
of full names, and you’ll develop a Java class to access the database using JDBC.You’ll develop the SQL query using the Data tools in WTP
The Data tools in WTP use JDBC to access databases WTP has the-box support for many databases and, with a little Eclipse plug-in develop-ment effort, others can be added Virtually all databases have JDBC drivers,
out-of-so you have lots of choices available, but for purposes of illustration you’lluse Apache Derby Derby is very suitable for development with WTP because
it is Open Source, pure Java, and can be embedded easily in Web applications
If you have another supported database already installed, feel free to use it.Just modify the following instructions accordingly
Trang 24You’ll perform the following development tasks in this iteration:
1 Connect to a Database
2 Execute SQL Statements
3 Add Database Access to a Web Application
Refer to Chapter 9 for more detail
Connect to a Database
Add a database connection to your project as follows:
Figure 3.25 Derby Plug-In
Trang 25Iteration 3: Database Access 73
Figure 3.26 Show View—Data Views
1 WTP provides two views for working with databases: Database Explorerand Data Output The Database Explorer view lets you connect to databasesand examine their contents The Data Output view lets you see the results
of executing SQL statements on a database Add these views to the J2EEperspective as follows:
a Invoke the Window 䉴 Show View䉴 Othercommand from the menu bar
to open the Show View dialog
b Expand the Data category (see Figure 3.26), select the Database Explorerand Data Output views, and click the OK button
2 WTP adds these views to the J2EE perspective (see Figure 3.27) Feel free torearrange these views according to your personal tastes
3 To work with a database, you need to add a new connection to the DatabaseExplorerview In the Database Explorer view, select the Connections folder,right click, and invoke the New Connection command from the contextmenu This opens the New Connection wizard Create a new connection toDerby as follows:
a Select Derby 10.1 as the database manager
b Select Derby Embedded JDBC Driver as the JDBC driver
c Enter a convenient directory, for example, C:\web1db, as the Databaselocation This should either be a nonexistent directory or a directory
Trang 26that contains a previously created Derby database If the directory isnonexistent, make sure that the Create the database if required checkbox
is checked To delete a Derby database, simply delete its directory.Enter the location of derby.jaras the Class location If you installed theDerby plug-in (see Figure 3.25 in the previous sidebar), then derby.jarislocated in the pluginsdirectory in the
org.apache.derby.core
directory
Click the Test Connection button to verify that your connection is
configured correctly If you specified a nonexistent directory, then testingthe connection will create the database (see Figure 3.28)
Click the Finish button to create the connection
Figure 3.27 J2EE Perspective with Data Views
Trang 27Iteration 3: Database Access 75
4 When the New Connection wizard completes, a new connection appears inthe Database Explorer view You can now explore the database by expandingthe connection to see its schemas, tables, columns, and other database com-ponents You can view the contents of a table as follows: Select a table andinvoke the Data䉴 Sample Contentscommand from the context menu Thecontents of the table will appear in the Data Output view You’re now ready
to create a table for your Web application and populate it with some data
Execute SQL Statements
WTP lets you interactively execute SQL statements in a database using the SQLScrapbook editor The SQL Scrapbook editor is associated with files that haveextension*.sqlpage.Do the following to execute some SQL statements:
Figure 3.28 New Connection Wizard
Trang 281 Open the SQL Scrapbook editor on a new page by clicking the Open SQLScrapbookicon in the Database Explorer view When prompted, createthe new SQL scrapbook page in the Web1directory, give it the name web1db,and associate it with the web1dbconnection you previously created.
Note that you can also open the editor by running the New wizard andselecting the SQL Scrapbook Page file type from the Data category
2 Enter the SQL statements as shown in the editor (see Figure 3.29) Thesestatements create a table, populate it with three rows of data, and query it.The last query is what you’ll use in your Web application to look up the fullname for a given user id
Figure 3.29 SQL Editor—web 1db.sqlpage
Note that SQL scrapbook pages are actually XML files They contain thedatabase connection information as well as the SQL statements that arewrapped in a CDATAsection (see Example 3.4) If you see the XML tags whenediting, then you have not opened the file in the SQL editor To remedy this,simply close the editor and reopen the page with the SQL editor
Trang 29Iteration 3: Database Access 77
Example 3.4 Listing of web1db.sqlpage
<?xml version="1.0" encoding="UTF-8"?>
<SQLPage nameConnection="web1db">
<Statement><![CDATA[CREATE TABLE WEB1.LOGIN
(USERID CHAR(8) NOT NULL, FULLNAME CHAR(20), PRIMARY KEY(USERID)); INSERT INTO WEB1.LOGIN (USERID, FULLNAME)
VALUES ('dai','Naci Dai');
INSERT INTO WEB1.LOGIN (USERID, FULLNAME)
VALUES ('mandel','Lawrence Mandel');
INSERT INTO WEB1.LOGIN (USERID, FULLNAME)
VALUES ('ryman','Arthur Ryman');
SELECT * FROM WEB1.LOGIN ORDER BY FULLNAME;
SELECT FULLNAME FROM WEB1.LOGIN WHERE USERID = 'ryman';
]]></Statement>
</SQLPage>
3 In the SQL Scrapbook editor, click anywhere and execute all the statements
by invoking the Run SQL command from the context menu You can alsoexecute individual statements by selecting them and invoking the com-mand Note that the statements are delimited by the semicolon character.You can change this using a menu command When each statement is exe-cuted, an entry is made in the Data Output view For the SELECTstatement,you can view the result set by clicking on the Results tab (see Figure 3.30)
Figure 3.30 Data Output View Results Tab
4 You have now created and populated the database, and executed somequeries against it You are ready to add the lookup query to your Webapplication
Before proceeding, you need to disconnect from the Derby database Selecttheweb1dbconnection in the Database Explorer view and invoke the
Disconnectcommand from the context menu This cleanly shuts down theconnection and lets other applications connect to the Derby database
Trang 30Add Database Access to a Web Application
In order to add database access to your Web application you need to make thedatabase driver available to it Do the following to add Derby access to yourWeb application:
1 The simplest way to add Derby access to a Web application is to copyderby.jarinto the WEB-INF/libdirectory The WEB-INF/libdirectory of aJ2EE Web application is precisely intended to hold any JAR files that theapplication needs Copy derby.jarintoWEB-INF/libnow
Disconnect Derby from Data Tools
Derby only supports connections from one process at a time.The Data tools establish
a connection to the Derby database, and this locks out the Web application from currently connecting to it Be sure to disconnect from Derby when you are finishedusing the Data tools so you can access Derby from your Web application
con-Using Derby with Multiple Web Applications
Although this technique for adding Derby support is simple, it is limited to caseswhere only one Web application needs Derby access If more than one applicationneeds Derby access, Derby must be configured differently In that case a shared copy
of Derby must be used, and it must be initialized and shut down properly by Tomcat
Refer to the tutorial Apache Derby Fortune Server Tutorial [Anderson2006] by Jean Anderson or the article Integrating Cloudscape and Tomcat [Bader2004] by Lance
Bader for instructions on how to configure a shared copy of the database
2 You’ll add the lookup query to your Web application by creating a newJava class, Database.java.Create a new Java class in the same package asHelloServletand enter its code (see Example 3.5) When entering thiscode, be sure to update the database connection URL string
"jdbc:derby:C:\\web1db"
to match the location of your database
Example 3.5 Listing of Database.java
package org.example.ch03;
import java.sql.Connection;
import java.sql.DriverManager;
Trang 31Iteration 3: Database Access 79
* the user id string
* @return the full name string
* @throws SQLException
* if a database problem occurs
*/
public String lookupFullname(String userid) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultset = null;
String fullname = "";
String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
String URL = "jdbc:derby:C:\\web1db";
String QUERY = "SELECT FULLNAME FROM WEB1.LOGIN WHERE USERID = ?"; try {
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultset != null) resultset.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
return fullname;
}
}
Trang 32TheDatabaseclass has a single method, lookupFullname, that takes theuser id as input and returns the full name as output This method performsdirect database access using JDBC calls.
In general, the business logic of your application should not directly accessthe database since that makes maintenance difficult Here the Databaseclass is the data access layer that isolates the rest of the application fromthe details of the database
However, JDBC is a low-level API, and its use is error prone It is preferable touse a higher-level persistence framework such as Java Persistence API (JPA),Hibernate, JDO, or Entity EJBs JDBC is used here for simplicity and pur-poses of illustration
3 Now modify your Web application to use the Databaseclass UpdateHelloServletto call the Databaseclass and add the full name to the
request (see Example 3.6, which has modified lines in bold font)
Example 3.6 Listing of Modified HelloServlet.java
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { String url = "/hello-world.jsp";
String user = request.getParameter("user");
if (user == null || user.length() == 0) {
url = "/login-user.jsp";
request.setAttribute("error", "User name must not be empty."); } else {
try {
Trang 33String fullname = new Database().lookupFullname(user);
request.setAttribute("fullname", fullname);
} catch (SQLException e) { e.printStackTrace();
} }
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url); dispatcher.forward(request, response);
}
}
4 Finally, modify hello-world.jspto display the full name Add the scriptlet(see Example 3.7; modified lines are in bold font) Here the scriptletchecks for the presence of an attribute named fullnamein the request Ifthe attribute is present, it is displayed to the user
Example 3.7 Listing of Modified hello-world.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
String user = request.getParameter("user");
if (user != null) person = user;
Object fullname = request.getAttribute("fullname");
if (fullname != null) person = fullname e.toString();
Trang 34Summary of Iteration 3
In this iteration you added the Data tools views to your perspective, created aconnection to the Derby database, used the SQL Scrapbook to interactively exe-cute SQL statements and view the results, created a Java class to access thedatabase using JDBC, and added this class into your Web application to look
up user names
Although JDBC access was used here, you should consider using a persistenceframework, such as JPA, in your Web application WTP 1.5 includes the Dali JPATools incubator subproject, which will become a component of JST in WTP 2.0
Iteration 4: Web Services
Web services are a way to let your Web application become integrated into otherapplications The topic of Web services is covered in much more detail inChapter 10 A brief discussion is given here
Web services are like ordinary Web pages except that instead of HTML, Webservices return pure data in XML and other formats so other applications can use
Figure 3.31 Web Browser—hello-world.jsp
Trang 35it Web services often use SOAP to format and process messages The capabilities
of a Web service are described by a WSDL document that software toolkits canprocess, typically to generate client access code J2EE contains Web services speci-
fications such as JSR 101: Java APIs for XML-based RPC (JAXRPC) [JSR101] and JSR 109: Implementing Enterprise Web Services [JSR109].
You’ll conclude the development of your Web application by deploying theDatabaseclass as a Web service This will let other applications programmaticallyget the full name of a user, given their user id WTP contains a very complete set
of extensible Web service tools You’ll use the Web Service wizard to deploy theWeb service, generate a client proxy for it, create a JSP test client application thatuses the proxy, and set up a TCP/IP monitor so you can view the SOAP trafficthat flows between the client and service The Web Service wizard performs allthese tasks for you without requiring you to write any code
Deploying a Web service requires that a suitable Web service runtime,
some-times referred to as a SOAP engine, be available for your application server.
WTP comes with out-of-the-box support for Apache Axis 1.3 and will supportAxis2 1.0 in the future Axis is very suitable for development with WTP because
it is an Open Source, pure Java, lightweight SOAP engine that works well withTomcat and that implements JAX-RPC However, the Web Service wizard isextensible, so with a little plug-in development work, other SOAP engines can beadded
You’ll perform the following development tasks in this iteration:
1 Deploy a Web service
2 Use a Test Client
3 Monitor SOAP Messages
Refer to Chapter 10 for more detail
Deploy a Web Service
Do the following to deploy your Java class as a Web service:
1 Deploying your Java class as a Web service is simple Just select
Database.javaand invoke the Web Services䉴Create Web servicecommandfrom the context menu This opens the Web Service wizard (see Figure 3.32).The Web Service wizard is very powerful and extensible It brings togethermany of the tasks you normally perform in the course of Web servicedevelopment
The wizard has two sliders The top one controls the service and the bottom one the client Both the service and client are deployed as Web
Trang 36applications When you create a service, you often also want to test itusing a client, so you use both sliders When you want to access a servicethat was previously created, you just use the bottom slider.
Figure 3.32 Web Service Wizard
The wizard also lets you set up a monitor that sits between the service andthe client and records the message traffic between them This is handy whenyou are trying to understand what the service is sending or if you want totest it for compliance with a Web Service Interoperability (WS-I) profile.Finally, the wizard lets you publish a service to a UDDI registry Refer toChapter 10 for more detail
Since you opened the wizard by selecting a Java class, the wizard is set to
perform the Bottom up Java Bean Web Service scenario The term bottom up
describes the development approach where you start with an tion class and deploy it as a Web service In this approach, the WSDL forthe service is automatically generated from the implementation class The
Trang 37implementa-Iteration 4: Web Services 85
term top down describes the approach of designing the WSDL first and
generating the skeleton of an implementation class from it Designing theWSDL first also requires that you have some skill with XML Schema, butthe extra effort can result in much cleaner and interoperable Web serv-ices As you might guess, the wizard also supports the top-down
approach Both the bottom-up and top-down approaches can be usedwith ordinary Java classes or EJBs
2 You will now use the wizard to deploy the Java class as a Web service,generate a Java client proxy to access it, generate a JSP test client applica-tion to exercise the client proxy, and monitor the SOAP messages
The wizard lets you set up both a service and a client, each of which goes
through a life cycle consisting of these steps: develop, assemble, deploy,
install, and test Sliders let you control how many of these steps the wizard
performs The wizard also lets you optionally publish the service to a istry and monitor its message traffic
reg-Move the service slider to its topmost position (Test service) This starts theapplication server after the Web service is deployed, making it ready tohandle requests
Move the client slider to its topmost position (Test client) This generates aJava client proxy and a JSP test client application, deploys it, and starts it,making it ready to send requests
Check the Monitor the Web service checkbox This configures and starts aTCP/IP monitor since we want to monitor the SOAP messages This optionalso configures the JSP test client to send requests to the TCP/IP monitor,which then forwards them to the Web service
Click the Finish button The wizard is smart enough to do all the rightthings
If you are really curious about the steps that the wizard performs, thenclick the Next button instead of Finish and look at all the pages that com-prise the wizard
The wizard does a lot of work for you It installs the SOAP engine, for ple, Axis 1.3, in the application if this is the first Web service you are deploying.The SOAP engine is responsible for sending and receiving XML messages overHTTP, and converting them into calls on your Java objects Installation of theSOAP engine involves copying the required JAR files into the Web module andupdating the Web deployment descriptor with entries for servlets that handleboth Web service requests and administration