Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

Web Applications

Web Application Life Cycle

Web Modules

Packaging Web Modules

Deploying a WAR File

Setting the Context Root

Deploying a Packaged Web Module

Testing Deployed Web Modules

Listing Deployed Web Modules

Updating Web Modules

Updating a Packaged Web Module

Dynamic Reloading

Undeploying Web Modules

Duke's Bookstore Examples

Accessing Databases from Web Applications

Populating the Example Database

Creating a Data Source in the Application Server

Further Information about Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

Configuring Web Applications

Web applications are configured by means of elements contained in the web application deployment descriptor.

The following sections give a brief introduction to the web application features you will usually want to configure. A number of security parameters can be specified; these are covered in Chapter 30, Securing Web Applications.

In the following sections, examples demonstrate procedures for configuring the Hello, World application. If Hello, World does not use a specific configuration feature, the section gives references to other examples that illustrate how to specify the deployment descriptor element.

Mapping URLs to Web Components

When a request is received by the web container 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 application and a web component. A URL path contains the context root and an alias:

http://host:port/context-root/alias
Setting the Component Alias

The alias identifies the web component that should handle a request. The alias path must start with a forward slash (/) and end with a string or a wildcard expression with an extension (for example, *.jsp). Since web containers automatically map an alias that ends with *.jsp, you do not have to specify an alias for a JSP page unless you wish to refer to the page by a name other than its file name.

The hello2 application has two servlets that need to be mapped in the web.xml file. You can edit a web application’s web.xml file in NetBeans IDE by doing the following:

  1. Select File→Open Project.

  2. In the Open Project dialog, navigate to:

    tut-install/javaeetutorial5/examples/web/
  3. Select the hello2 folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Expand the project tree in the Projects pane.

  7. Expand the Web pages node and then the WEB-INF node in the project tree.

  8. Double-click the web.xml file inside the WEB-INF node.

The following steps describe how to make the necessary edits to the web.xml file, including how to set the display name and how to map the servlet components. Because the edits are already in the file, you can just use the steps to view the settings.

To set the display name:

  1. Click General at the top of the editor to open the general view.

  2. Enter hello2 in the Display Name field.

To perform the servlet mappings:

  1. Click Servlets at the top of the editor to open the servlets view.

  2. Click Add Servlet.

  3. In the Add Servlet dialog, enter GreetingServlet in the Servlet Name field.

  4. Enter servlets.GreetingServlet in the Servlet Class field.

  5. Enter /greeting in the URL Pattern field.

  6. Click OK.

  7. Repeat the preceding steps, except enter ResponseServlet as the servlet name, servlets.ResponseServlet as the servlet class, and /response as the URL pattern.

If you are not using NetBeans IDE, you can add these settings using a text editor.

To package the example with NetBeans IDE, do the following:

  1. Select File→Open Project.

  2. In the Open Project dialog, navigate to:

    tut-install/javaeetutorial5/examples/web/
  3. Select the hello2 folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. In the Projects tab, right-click the hello2 project and select Build.

To package the example with the Ant utility, do the following:

  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/hello2/.

  2. Type ant. This target will build the WAR file and copy it to the tut-install/javaeetutorial5/examples/web/hello2/dist/ directory.

To deploy the example using NetBeans IDE, right-click on the project in the Projects pane and select Undeploy and Deploy.

To deploy the example using Ant, type ant deploy. The deploy target in this case gives you an incorrect URL to run the application. To run the application, please use the URL shown at the end of this section.

To run the application, first deploy the web module, and then open the URL http://localhost:8080/hello2/greeting in a browser.

Declaring Welcome Files

The welcome files mechanism allows you to specify a list of files that the web container will use for appending to a request for a URL (called a valid partial request) that is not mapped to a web component.

For example, suppose you define a welcome file welcome.html. When a client requests a URL such as host:port/webapp/directory, where directory is not mapped to a servlet or JSP page, the file host:port/webapp/directory/welcome.html is returned to the client.

If a web container receives a valid partial request, the web container examines the welcome file list and appends to the partial request each welcome file in the order specified and checks whether a static resource or servlet in the WAR is mapped to that request URL. The web container then sends the request to the first resource in the WAR that matches.

If no welcome file is specified, the Application Server will use a file named index.XXX, where XXX can be html or jsp, as the default welcome file. If there is no welcome file and no file named index.XXX, the Application Server returns a directory listing.

To specify a welcome file in the web application deployment descriptor using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Do one of the following, making sure that the JSP pages you specify are actually included in the WAR file:

    1. Click Pages at the top of the editor pane and enter the names of the JSP pages that act as welcome files in the Welcome Files field.

    2. Click XML at the top of the editor pane, specify the JSP pages using welcome-file elements and include these elements inside a welcome-file-list element. The welcome-file element defines the JSP page to be used as the welcome page.

      The example discussed in Encapsulating Reusable Content Using Tag Files has a welcome file.

Setting Initialization Parameters

The web components in a web module share an object that represents their application context (see Accessing the Web Context). You can pass initialization parameters to the context or to a web component.

To add a context parameter using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click General at the top of the editor pane.

  6. Select the Context Parameters node.

  7. Click Add.

  8. In the Add Context Parameter dialog, do the following:

    1. Enter the name that specifies the context object in the Param Name field.

    2. Enter the parameter to pass to the context object in the Param Value field.

    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the context object

  • A param-value element that specifies the parameter to pass to the context object

  • A context-param element that encloses the previous two elements

For a sample context parameter, see the example discussed in The Example JSP Pages.

To add a web component initialization parameter using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click Servlets at the top of the editor pane.

  6. After entering the servlet’s name, class, and URL pattern, click the Add button under the Initialization Parameters table.

  7. In the Add Initialization Parameter dialog:

    1. Enter the name of the parameter in the Param Name field.

    2. Enter the parameter’s value in the Param Value Field.

    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the name of the initialization parameter

  • A param-value element that specifies the value of the initialization parameter

  • An init-param element that encloses the previous two elements

Mapping Errors to Error Screens

When an error occurs during execution of a web application, you can have the application display a specific error screen according to the type of error. In particular, 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 (see Handling Servlet Errors) and any type of error screen.

To set up error mappings using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click Pages at the top of the editor pane.

  6. Expand the Error Pages node.

  7. Click Add.

  8. In the Add Error Page dialog:

    1. Click Browse to locate the page that you want to act as the error page.

    2. Enter the HTTP status code that will cause the error page to be opened in the Error Code field.

    3. Enter the exception that will cause the error page to load in the Exception Type field.

    4. Click OK.

Alternatively, you can click XML at the top of the editor pane and enter the error page mapping by hand using the following elements:

  • An exception-type element specifying either the exception or the HTTP status code that will cause the error page to be opened.

  • A location element that specifies the name of a web resource to be invoked when the status code or exception is returned. The name should have a leading forward slash (/).

  • An error-page element that encloses the previous two elements.

You can have multiple error-page elements in your deployment descriptor. Each one of the elements identifies a different error that causes an error page to open. This error page can be the same for any number of error-page elements.


Note - You can also define error screens for a JSP page contained in a WAR. If error screens are defined for both the WAR and a JSP page, the JSP page’s error page takes precedence. See Handling JSP Page Errors.


For a sample error page mapping, see the example discussed in The Example Servlets.

Declaring Resource References

If your web component uses objects such as enterprise beans, data sources, or web services, you use Java EE annotations to inject these resources into your application. Annotations eliminate a lot of the boilerplate lookup code and configuration elements that previous versions of Java EE required.

Although resource injection using annotations can be more convenient for the developer, there are some restrictions from using it in web applications. First, you can only inject resources into container-managed objects. This is because a container must have control over the creation of a component so that it can perform the injection into a component. As a result, you cannot inject resources into objects such as simple JavaBeans components. However, JavaServer Faces managed beans are managed by the container; therefore, they can accept resource injections.

Additionally, JSP pages cannot accept resource injections. This is because the information represented by annotations must be available at deployment time, but the JSP page is compiled after that; therefore, the annotation will not be seen when it is needed. Those components that can accept resource injections are listed in Table 3-1.

This section describes how to use a couple of the annotations supported by a servlet container to inject resources. Chapter 25, Persistence in the Web Tier describes how web applications use annotations supported by the Java Persistence API. Chapter 30, Securing Web Applications describes how to use annotations to specify information about securing web applications.

Table 3-1 Web Components That Accept Resource Injections

Component

Interface/Class

Servlets

javax.servlet.Servlet

Servlet Filters

javax.servlet.ServletFilter

Event Listeners

javax.servlet.ServletContextListener

javax.servlet.ServletContextAttributeListener

javax.servlet.ServletRequestListener

javax.servlet.ServletRequestAttributeListener

javax.servlet.http.HttpSessionListener

javax.servlet.http.HttpSessionAttributeListener

javax.servlet.http.HttpSessionBindingListener

Taglib Listeners

Same as above

Taglib Tag Handlers

javax.servlet.jsp.tagext.JspTag

Managed Beans

Plain Old Java Objects

Declaring a Reference to a Resource

The @Resource annotation is used to declare a reference to a resource such as a data source, an enterprise bean, or an environment entry. This annotation is equivalent to declaring a resource-ref element in the deployment descriptor.

The @Resource annotation is specified on a class, method or field. The container is responsible for injecting references to resources declared by the @Resource annotation and mapping it to the proper JNDI resources. In the following example, the @Resource annotation is used to inject a data source into a component that needs to make a connection to the data source, as is done when using JDBC technology to access a relational database:

@Resource javax.sql.DataSource catalogDS;
public getProductsByCategory() {
    // get a connection and execute the query
    Connection conn = catalogDS.getConnection();
    ..
}

The container injects this data source prior to the component being made available to the application. The data source JNDI mapping is inferred from the field name catalogDS and the type, javax.sql.DataSource.

If you have multiple resources that you need to inject into one component, you need to use the @Resources annotation to contain them, as shown by the following example:

@Resources ({
    @Resource (name="myDB" type=java.sql.DataSource),
    @Resource(name="myMQ" type=javax.jms.ConnectionFactory)
})

The web application examples in this tutorial use the Java Persistence API to access relational databases. This API does not require you to explicitly create a connection to a data source. Therefore, the examples do not use the @Resource annotation to inject a data source. However, this API supports the @PersistenceUnit and @PersistenceContext annotations for injecting EntityManagerFactory and EntityManager instances, respectively. Chapter 25, Persistence in the Web Tier describes these annotations and the use of the Java Persistence API in web applications.

Declaring a Reference to a Web Service

The @WebServiceRef annotation provides a reference to a web service. The following example shows uses the @WebServiceRef annotation to declare a reference to a web service. WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service’s WSDL file:

...
import javax.xml.ws.WebServiceRef;
...
public class ResponseServlet extends HTTPServlet {
@WebServiceRef(wsdlLocation=
    "http://localhost:8080/helloservice/hello?wsdl")
static HelloService service;