Web Service Applications

 

 


Overview

There are two types of Web app components:

  1. Java Servlets

    Java programming language classes that dynamically process requests and construct responses. Best suited to service-oriented webapps and managing the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data.

  2. Java Server Pages

    Text-based documents that execute as servlets. Appropriate for generating pages marked up with HTML, SVG, WML, and XML.

In the Java Web Services Developer Pack, web applications run in the Tomcat web container. Most webapps use the HTTP protocol.

 


Web Application Life Cycle

The process for creating, deploying, and executing a webapp can be summarized as follows:

  1. Develop the Web component code
  2. Develop a deployment descriptor.
  3. Build the webapp components along with any static resources (for example, images) and helper classes referenced by the component.
  4. Install or deploy the application into a Web container.
  5. Access a URL that references the webapp.

 


Web Application Archives

webapps are packaged in a webapp archive (WAR), which are similar to JARs used for Java class libraries. WARs can contain:

Web components and static Web content files are called Web resources.

A webapp can run from a WAR file or from an unpacked directory laid out in the same format as a WAR.

 

WAR Directory Structure

The top-level directory of a WAR is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static Web resources are stored.

The document root contains a subdirectory called WEB-INF, which contains the following files and directories:

web.xml webapp deployment descriptor
Tag Library Descriptor Files
classes Directory that contains server-side classes, including servlets, utility classes, and JavaBeans components
lib Directory that contains JAR archives of libraries, including tag libraries and any utility libraries called by server-side classes)

You can also create application-specific subdirectories (that is, package directories) in either the document root or the WEB-INF/classes directory.

 

WebApp Directory Structure

The source code for web applications is stored in the following structure under ../webapp:

build.xml Ant build file
context.xml Optional application configuration file
src Java source of servlets and JavaBeans components
web JSP pages and HTML pages, images

The Ant build files (build.xml) distributed with the examples contain targets to create an unpacked WAR structure in the build subdirectory of webapp, copy and compile files into that directory, and invoke the manager commands via special Ant tasks to install, reload, remove, deploy, and undeploy applications. The example Ant targets are:

prepare Creates build directory and WAR subdirectories.
build Compiles and copies the webapp webapp files into the build directory.
install Notifies Tomcat to install an application using the Ant install task.
reload Notifies Tomcat to reload the application using the Ant reload task.
deploy Notifies Tomcat to deploy the application using the Ant deploy task.
undeploy Notifies Tomcat to undeploy the application using the Ant undeploy task.
remove Notifies Tomcat to remove the application using the Ant remove task.

 

Creating a WAR file

You can manually create a WAR in two ways:

  1. With the jar command:

    jar cvf webapp.war .
    

  2. With the Ant war task

Both of these methods require you to have created a webapp deployment descriptor.

You can also package an application into a WAR using deploytool. When you use deploytool, it creates a webapp deployment descriptor based on information entered into deploytool wizards and inspectors. To build and package the Hello1 application into a WAR named hello1.war:

  1. cd to $TOMCAT_HOME/webapps/examples/web/hello1.

  2. Run ant build. The build target will spawn any necessary compilations and copy files to the $TOMCAT_HOME/webapps/examples/web/hello1/build directory.

  3. Start deploytool.

  4. Create a webapp called hello1.

    1. Select "File | New Web Application".

    2. Select the Create New Stand-Alone WAR Module.

    3. Click Browse and in the file chooser, navigate to $TOMCAT_HOME/webapps/examples/web/hello1.

    4. In the File Name field, enter hello1.

    5. Click Choose Module File.

    6. In the WAR Display Name field enter hello1.

  5. Add the greeting Web component and all of the Hello1 application content.

    1. Click Edit to add the content files.

    2. In the Edit Contents dialog, select $TOMCAT_HOME/webapps/examples/web/hello1/build/duke.waving.gif and click Add. Navigate to WEB-INF/classes and select GreetingServlet.class, and ResponseServlet.class and click Add. Click OK.

    3. Click Next.

    4. Select the Servlet radio button.

    5. Click Next.

    6. Select GreetingServlet from the Servlet Class combo box.

    7. Click Finish.

  6. Add the response Web component.

    1. Select "File | Edit Web Application".

    2. Click the Add to Existing WAR Module radio button and select hello1 from the combo box. Since the WAR contains all of the servlet classes, you do not have to add any more content.

    3. Click Next.

    4. Select the Servlet radio button.

    5. Click Next.

    6. Select ResponseServlet from the Servlet Class combo box.

    7. Click Finish.

 


Configuring Web Applications

webapps are configured via elements contained in webapp deployment descriptors. You can either manually create descriptors using a text editor or use deploytool to generate descriptors for you. The following sections give a brief introduction to the webapp features you will usually want to configure. A number of security parameters can be specified.

In the following sections, some examples demonstrate procedures for configuring the Hello, World application. If Hello,World does not use a specific configuration feature, the section gives uses other examples for illustrating the deployment descriptor element and describes generic procedures for specifying the feature using deploytool. Descriptor elements must appear in the deployment descriptor in the following order: icon, display-name, description, distributable, context-param, filter, filter-mapping, listener, servlet, servlet-mapping, session-config, mime-mapping, welcome-file-list, error-page, taglib, resource-env-ref, resource-ref, security-constraint, login-config, security-role, env-entry.

 

Prolog

Since the deployment descriptor is an XML document, it requires a prolog. The prolog of the webapp deployment descriptor is as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web 
Application 2.3//EN" "http://java.sun.com/dtd/web-
app_2_3.dtd"> 

 

Alias Paths

When a request is received by Tomcat it must determine which Web component should handle the request. It does so by mapping the URL path contained in the request to a Web component. A URL path contains the context root and an alias path


Before a servlet can be accessed, the Web container must have least one alias path for the component. The alias path must start with a / and end with a string or a wildcard expression with an extension (*.jsp, for example). Since Web containers automatically map an alias path that ends with *.jsp, you do not have to specify an alias path for a JSP page unless you wish to refer to the page by a name other than its file name.

To set up the mappings servlet version of the Hello application in the Web deployment descriptor, add the following servlet and servlet-mapping elements to the webapp deployment descriptor. To define an alias for a JSP page, replace the servlet-class subelement with a jsp-file subelement in the servlet element.

<servlet>
 <servlet-name>greeting</servlet-name>
 <display-name>greeting</display-name>
 <description>no description</description>
 <servlet-class>GreetingServlet</servlet-class>
</servlet>
<servlet>
 <servlet-name>response</servlet-name>
 <display-name>response</display-name>
 <description>no description</description>
 <servlet-class>ResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>greeting</servlet-name>
 <url-pattern>/greeting</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>response</servlet-name>
 <url-pattern>/response</url-pattern>
</servlet-mapping>

To set up the mappings for the servlet version of the Hello application in deploytool:

  1. Select the hello1 WAR.
  2. Select the GreetingServlet Web component.
  3. Select the Aliases tab.
  4. Click Add to add a new mapping.
  5. Type /greeting in the aliases list.
  6. Select the ResponseServlet Web component.
  7. Click Add.
  8. Type /response in the aliases list.

 

Context and Initialization Parameters

The Web components in a WAR share an object that represents their application context. You can pass parameters to the context or Web component. To do so add a context-param or init-param element to the webapp deployment descriptor. context-param is a subelement of the top-level web-app element. init-param is a subelement of the servlet element. Here is the element used to declare a context parameter that sets a resource bundle:

<web-app>
 <context-param>
  <param-name>
   javax.servlet.jsp.jstl.fmt.localizationContext
  </param-name>
  <param-value>messages.BookstoreMessages</param-value>
 </context-param>
 ...
</web-app>

To add a context parameter in deploytool:

  1. Select the WAR.
  2. Select the Context tab.
  3. Click Add.

To add an initialization parameter in deploytool:

  1. Select the Web component.
  2. Select the Init Param. tab.
  3. Click Add.

 

Event Listeners

To add an event listener class add a listener element to the webapp deployment descriptor. Here is an element that declares a listener class:

<listener>
 <listener-class>listeners.ContextListener</listener-class>
</listener>

To add an event listener in deploytool:

  1. Select the WAR.
  2. Select the Event Listeners tab.
  3. Click Add.
  4. Select the listener class from the new field in the Event Listener Classes pane.

 

Filter Mappings

A Web container uses filter mapping declarations to decide which filters to apply to a request, and in what order. The container matches the request URI to a servlet. To determine which filters to apply, it matches filter mapping declarations by servlet name or URL pattern. The order in which filters are invoked is the order in which filter mapping declarations that match a request URI for a servlet appear in the filter mapping list.

To specify a filter mapping, add an filter and filter-mapping elements to the webapp deployment descriptor. Here is the element used to declare the order filter and map it to a ReceiptServlet:

<filter>
 <filter-name>OrderFilter<filter-name>
 <filter-class>filters.OrderFilter<filter-class>
</filter>
<filter-mapping>
 <filter-name>OrderFilter</filter-name>
 <url-pattern>/receipt</url-pattern>
</filter-mapping>

To add a filter in deploytool:

  1. Select the WAR.
  2. Select the Filter Mapping tab.
  3. Add a filter.
    1. Click Edit Filter List.
    2. Click Add.
    3. Select the filter class.
    4. Enter a filter name.
    5. Add any filter initialization parameters.
    6. Click OK.
  4. Map the filter.
    1. Click Add.
    2. Select the filter name.
    3. Select the target type. A filter can be mapped to a specific servlet or to all servlets that match a given URL pattern.
    4. Specify the target. If the target is a servlet, select the servlet from the drop-down list. If the target is a URL pattern, enter the pattern.

 

Error Mappings

You can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any Web component and a Web resource. To set up the mapping, add an <error-page> element to the deployment descriptor. Here is an element used to map OrderException to the errorpage.html.

<error-page>
 <exception-type>exception.OrderException</exception-type>
 <location>/errorpage.html</location>
</error-page>

To add an error mapping in deploytool:

  1. Select the WAR.
  2. Select the File Refs tab.
  3. Click Add in the Error Mapping pane.
  4. Enter the HTTP status code or fully-qualified class name of an exception in the Error/Exception field.
  5. Enter the name of a resource to be invoked when the status code or exception is returned. The name should have a leading forward slash /.
You can also define error pages for a JSP page contained in a WAR. If error pages are defined for both the WAR and a JSP page, the JSP page's error page takes precedence.

 

References to Environment Entries, Resource Environment Entries, or Resources

If your Web components reference environment entries, resource environment entries, or resources such as databases, declare the references with <env-entry>, <resource-env-ref>, or <resource-ref> elements in the webapp deployment descriptor. Here is an element used to declare a reference to the data source:

<resource-ref>
 <res-ref-name>jdbc/BookDB</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

To add a reference in deploytool:

  1. Select the WAR.
  2. Select the Environment, Enterprise Bean Refs, Resource Env. Refs, or Resource Refs tab.
  3. Click Add in the pane to add a new reference.

 


Installing Web Applications

A context is a name that gets mapped to a webapp.

For example, the context of the Hello1 application is /hello1, and can be accessed at www.setgetweb.com/hello1.

Tomcat can be notified about new contexts using the Ant install task, which identifies the path and location using a attribute named "war". The value of the war attribute can be a WAR file or an unpacked directory.

<install url="url" 
         path="webapp" 
         war="file:build"
         username="username" 
         password="password" />

Instead of providing a war attribute, you can specify configuration information with the config attribute:

<install url="url" 
         path="webapp" 
         config="file:build/context.xml"
         username="username" 
         password="password"/>

The config attribute points to a configuration file that contains a context entry of the form:

<Context path="/bookstore1"
         docBase="../webapps/examples/web/bookstore1/build"
         debug="0">

Note that the context entry implicitly specifies the location of the webapp files through its docBase attribute.

The example build files contain an Ant install target that invokes the Ant install task:

<target name="install" 
        description="Install web application" 
        depends="build">
 <install url="${url}" 
          path="${webapp}"
          config="file:build/context.xml"
          username="${username}" 
          password="${password}"/>
</target>

The Ant install task requires that a webapp deployment descriptor (web.xml) be available. All of the example applications are distributed with a deployment descriptor.

To install the Hello1 application:

  1. cd to $TOMCAT_HOME/webapps/examples/web/hello1.

  2. Make sure Tomcat is started.

  3. Execute ant install. The install target notifies Tomcat that the new context is available.

 


Deploying Web Applications

There are several ways to permanently deploy a context to Tomcat:

  1. With the Ant deploy task:
     <deploy url="url" 
             path="webapp"
             war="file:/path/to/webapp.war"
             username="username" 
             password="password" />
    

    Unlike the install task, which can reference an unpacked directory, the deploy task requires a WAR. The task uploads the WAR to Tomcat and starts the application. You can deploy to a remote server with this task.

  2. With deploytool. The deploy operation copies the WAR to Tomcat, and notifies Tomcat of the new context.

    To deploy the Hello1 application using deploytool:

    • Select the hello1 WAR.
    • Select "Tools | Deploy".
    • Click OK to select the default context path /hello1.
    • Enter the user name and password that you supplied when you installed the Java WSDP.
    • Click Finish.
    • Dismiss the Deploy Console by clicking Close.

  3. Copy a webapp directory or WAR to $TOMCAT_HOME/webapps, then restart Tomcat.

  4. Copy a configuration file named webapp.xml containing a context entry to $TOMCAT_HOME/webapps, then restart Tomcat.

    Note that the context entry implicitly specifies the location of the webapp files through its docBase attribute. For example:

     <Context path="/bookstore1"
              docBase="../webapps/examples/web/bookstore1/build" 
              debug="0">
    

Some of the example build files contain an "ant deploy target" that invokes the Ant deploy task.

 


Listing Installed and Deployed Web Applications

If you want to list all webapps currently available on Tomcat you use the Ant list task:

<list url="url" username="username" password="password" />

The example build files contain an Ant list target that invokes the Ant list task.

You can also see list applications by running the Manager Application:


Finally, you can list the webapps running on a server with deploytool by selecting the server from the Server list in the left pane.

 


Running Web Applications

A webapp is executed when a Web browser references a URL that is mapped to component. Once you have installed or deployed the Hello1 application, you can run the webapp by pointing a browser at


Replace <host> with the name of the host running Tomcat. If your browser is running on the same host as Tomcat, you may replace <host> with localhost.

 


Updating Web Applications

During development, you will often need to make changes to webapps. After you modify a servlet,

  1. Recompile the servlet class.
  2. Update the application in the server.
  3. Reload the URL in the client.

When you update a JSP page, you do not need to recompile or reload the application, because Tomcat does this automatically.

To try this feature, modify the servlet version of the Hello application. For example, you could change the greeting returned by GreetingServlet to be:

<h3>Hi, my name is Duke. What's yours?</h3>

To update the file:

  1. Edit GreetingServlet.java in the source directory $TOMCAT_HOME/webapps/examples/web/hello1/src.
  2. Run ant build. This task recompiles the servlet into the build directory.

The procedure for updating the application in the server depends on whether you installed it using the Ant install task or deployed it using the Ant deploy task or deploytool.

 

Reloading Web Applications

If you have installed an application using the Ant install command, you update the application in the server using the Ant reload task:

<reload url="url" path="webapp"
 username="username" password="password" />

The example build files contain an Ant remove target that invokes the Ant remove task. Thus to update the Hello1 application in the server, execute ant reload. To view the updated application, reload the Hello1 URL in the client. Note that the reload task only picks up changes to Java classes, not changes to the web.xml file. To reload web.xml, remove the application and install it again.

You should see the screen in the browser:

Figure 4-3 New Greeting

To try this on the JSP version of the example, first build and deploy the JSP version of the Hello application:

  1. cd to $TOMCAT_HOME/webapps/examples/web/hello2.
  2. Run ant build. The build target will spawn any necessary compilations and copy files to the $TOMCAT_HOME/webapps/examples/web/hello2/build directory.
  3. Run ant install. The install target copies the build directory to $JWSDP_HOME/webapps and notifies Tomcat that the new application is available.

Modify one of the JSP files. Then run ant build to copy the modified file into webapps/examples/web/hello2/build. Remember, you don't have to reload the application in the server, because Tomcat automatically detects when a JSP page has been modified. To view the modified application, reload the Hello2 URL in the client.

 

Redeploying Web Applications

If you have deployed a webapp deploytool, you update it using deploytool as follows:

  1. Select the hello1 WAR.
  2. Select "Tools | Update Files".
  3. A dialog will appear listing the changed file. Verify that it is GreetingServlet.class and click OK twice.
  4. Select Tools | Update and Redeploy.
  5. A dialog will appear. Select /hello1 from the Select Webapp to redeploy combo box and click OK.
  6. Dismiss the Redeploy Console by clicking Close.

If you have deployed the application using the Ant deploy task you update the application by using the Ant undeploy task and then using the Ant deploy task.

 


Removing Web Applications

If you want to take an installed webapp out of service, you invoke the Ant remove task:

<remove url="url" path="webapp"
 username="username" password="password" />

The example build files contain an Ant remove target that invokes the Ant remove task.

 


Undeploying Web Applications

If you want to remove a deployed webapp, you use the Ant undeploy task:

<undeploy url="url" path="webapp"
 username="username" password="password" />

or deploytool's Undeploy command. For example, to undeploy the Hello1 application using deploytool:

  1. Select the hello1 WAR.
  2. Select Tools | Undeploy.
  3. A dialog will appear. Select /hello1 from the Select Webapp to undeploy combo box and Click OK.
  4. Dismiss the Undeploy Console by clicking Close.

or

  1. Select the server from the Server list in the left pane.
  2. Select the hello1 application in the Deployed Applications pane.
  3. Click Undeploy.

Some of the example build files contain an Ant undeploy target that invokes the Ant undeploy task.

 


Internationalizing and Localizing Web Applications

Internationalization is the process of preparing an application to support various languages and data formats. Localization is the process of adapting an internationalized application to support a specific language or locale. Although all client user interfaces should be internationalized and localized, it is particularly important for webapps because of the far-reaching nature of the Web. For a good overview of internationalization and localization, see

http://java.sun.com/docs/books/tutorial/i18n/index.html

There are two approaches to internationalizing a webapp:

In the following chapters on Web technology, the Duke's Bookstore example is internationalized and localized into English and Spanish. The key and value pairs are contained in list resource bundles named messages.BookMessage_*.class. To give you an idea of what the key and string pairs in a resource bundle look like, here are a few lines from the file messages.BookMessages.java.

{"TitleCashier", "Cashier"},
{"TitleBookDescription", "Book Description"},
{"Visitor", "You are visitor number "},
{"What", "What We"re Reading"},
{"Talk", " talks about how Web components can transform the way 
you develop applications for the Web. This is a must read for 
any self respecting Web developer!"},
{"Start", "Start Shopping"},

To get the correct strings for a given user, a Web component retrieves the locale (set by a browser language preference) from the request, opens the resource bundle for that locale, and then saves the bundle as a session attribute.

ResourceBundle messages = (ResourceBundle)session.
 getAttribute("messages");
 if (messages == null) {
  Locale locale=request.getLocale();
  messages = ResourceBundle.getBundle("WebMessages",
   locale); 
  session.setAttribute("messages", messages);
 }

A Web component retrieves the resource bundle from the session:

ResourceBundle messages =
 (ResourceBundle)session.getAttribute("messages");

and looks up the string associated with the key TitleCashier as follows:

messages.getString("TitleCashier");

This has been a very brief introduction to internationalizing webapps. For more information on this subject see the Java BluePrints:

http://java.sun.com/blueprints

 


Accessing Databases from Web Applications

Data that is shared between Web components and persistent between invocations of a webapp is usually maintained by a database. webapps use the JDBC 2.0 API to access relational databases. For information on this API, see

http://java.sun.com/docs/books/tutorial/jdbc

 

The Examples

For this release we have tested the examples with the PointBase 4.3 database and we provide an Ant build file to create the database tables and populate the database. The remainder of this section describes how to

 

Installing and Starting the Database Server

You can download an evaluation copy of the PointBase 4.3 database from:

http://www.pointbase.com

Make sure to choose a platform-specific (UNIX or Windows) installation package. Install the client and server components. After you have downloaded and installed the PointBase database, do the following:

  1. Add a pb.home property to your build.properties file that points to your PointBase install directory. On Windows the syntax of the entry must be
     pb.home=drive:\\<PB_HOME>
    
    
  2. Copy <PB_HOME>/lib/pbclient43.jar to <JWSDP_HOME>/common/lib to make the PointBase client library available to the example applications. If Tomcat is running, restart it so that it loads the client library.
  3. cd to <PB_HOME>/tools/server.
  4. Start the PointBase server by typing start_server on UNIX or startserver on Windows.

 

Populating the Database

  1. cd to $TOMCAT_HOME/webapps/examples/web.

  2. Execute ant. The default Ant task, create-book-db, uses the PointBase console tool to execute the SQL statements in books.sql. At the end of the processing, you should see the following output:

    [java] ID
    [java] ----------
    [java] 201
    [java] 202
    [java] 203
    [java] 204
    [java] 205
    [java] 206
    [java] 207
    [java]
    [java] 7 Rows Selected.
    [java]
    [java] SQL>
    [java]
    [java] COMMIT;
    [java] OK
    
    

 

Configuring the Web Application to Reference a Data Source

In order to access a database from a webapp, declare resource reference in the application's webapp deployment descriptor. The resource reference declares a JNDI name, the type of the data resource, and the kind of authentication used when the resource is accessed:

<resource-ref>
 <res-ref-name>jdbc/BookDB</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

The JNDI name is used to create a data source object in the database helper class database.BookDB used by the examples. The res-auth element specifies that the container will manage logging on to the database.

To specify a resource reference in deploytool:

  1. Select the WAR.
  2. Select the Resource Refs tab.
  3. Click Add.
  4. Enter jdbc/BookDB in the Coded Name field.

 

Defining a Data Source in Tomcat

In order to use a database create a data source in Tomcat. The data source contains information about the driver class and URL used to connect to the database and database login parameters. To define a data source in Tomcat, you use admintool as follows:

  1. Start admintool by opening a browser at:
     http://localhost:8080/admin/index.jsp
    
    
  2. Log in using the user name and password you specified when you installed the Java WSDP.
  3. Select the Data Sources entry under Resources.
  4. Select Available Actions | Create New Data Source.
  5. Enter pointbase in the JNDI Name field.
  6. Enter jdbc:pointbase:server://localhost/sample in the Data Source URL field.
  7. Enter com.pointbase.jdbc.jdbcUniversalDriver in the JDBC Driver Class field.
  8. Enter public in the User Name and Password fields.
  9. Click the Save button.
  10. Click the Commit button.

 

Configuring Tomcat to Map the JNDI Name to a Data Source

Since the resource reference declared in the webapp deployment descriptor uses a JNDI name to refer to the data source, connect the name to a data source by providing a resource link entry in Tomcat's configuration. Here is the entry used by the application discussed in all the Web technology chapters:

<Context path="/bookstore1"
 docBase="examples/web/bookstore1/build" 
 debug="0">
 <ResourceLink name="jdbc/BookDB" global="pointbase"/>
</Context>

Since the resource link is a subentry of the context entry, you add this entry to Tomcat's configuration in the same ways that you add the context entry: by passing the name of a configuration file containing the entry to the config attribute of the Ant install task or by copying the configuration file named webapp.xml that contains the context entry to $TOMCAT_HOME/webapps.

If you are deploying the application using the Ant deploy task, package a configuration file named context.xml containing the context entry in the META-INF directory of the WAR.

If you are deploying the application using deploytool, you make the connection as follows:

  1. Select the WAR.
  2. Select the Resource Refs tab.
  3. Select the data source defined earlier.
  4. Click the Import Data Sources button.
  5. Dismiss the confirmation dialog.
  6. Select pointbase from the drop down list.

 


Further Information

For further information on webapps and Tomcat see:


 

Home