The Java EE 6 Tutorial, Volume I

Chapter 3 Getting Started with Web Applications

A web application is a dynamic extension of a web or application server. There are two types of web applications:

The following topics are addressed here:

Web Applications

In the JavaTM EE platform, web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, web pages, web service endpoints, or JSP pages. The interaction between a web client and a web application is illustrated in Figure 3–1. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer PagesTM technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or it can pass the request to another web component. Eventually a web component generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client.

Figure 3–1 Java Web Application Request Handling

Diagram of web application request handling. Clients
and web components communicate using HttpServletRequest and HttpServletResponse.

Servlets are Java programming language classes that dynamically process requests and construct responses. Java technologies, such as JavaServerTM Faces and Facelets, and frameworks are used for building interactive web applications. Although servlets and Java Server Faces and Facelets pages can be used to accomplish similar things, each has its own strengths. Servlets are best suited for service-oriented applications (web service endpoints are implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data. Java Server Faces and Facelets pages are more appropriate for generating text-based markup, such as XHTML, and are generally used for presentation–oriented applications.

Web components are supported by the services of a runtime platform called a web container. A web container provides services such as request dispatching, security, concurrency, and life-cycle management. It also gives web components access to APIs such as naming, transactions, and email.

Certain aspects of web application behavior can be configured when the application is installed, or deployed, to the web container. The configuration information is maintained in a text file in XML format called a web application deployment descriptor (DD). A DD must conform to the schema described in the Java Servlet Specification.

This chapter gives a brief overview of the activities involved in developing web applications. First it summarizes the web application life cycle. Then it describes how to package and deploy very simple web applications on the Sun GlassFish Enterprise Server. It moves on to configuring web applications and discusses how to specify the most commonly used configuration parameters.

Web Application Life Cycle

A web application consists of web components, static resource files such as images, and helper classes and libraries. The web container provides many supporting services that enhance the capabilities of web components and make them easier to develop. However, because a web application must take these services into account, the process for creating and running a web application is different from that of traditional stand-alone Java classes.

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

  1. Develop the web component code.

  2. Develop the web application deployment descriptor.

  3. Compile the web application components and helper classes referenced by the components.

  4. Optionally package the application into a deployable unit.

  5. Deploy the application into a web container.

  6. Access a URL that references the web application.

Developing web component code is covered in the later chapters. Steps 2 through 4 are expanded on in the following sections and illustrated with a Hello, World-style presentation-oriented application. This application allows a user to enter a name into an HTML form (Figure 3–2) and then displays a greeting after the name is submitted (Figure 3–3).

Figure 3–2 Greeting Form

Screen capture of Duke's greeting, "Hello, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset
buttons.

Figure 3–3 Response

Screen capture of Duke's response, "Hello, Charlie!"

The Hello application contains two web components that generate the greeting and the response. This chapter discusses hello2, a servlet-based web application in which the components are implemented by two servlet classes (tut-install/examples/web/hello2/src/servlets/GreetingServlet.java and tut-install/examples/web/hello2/src/servlets/ResponseServlet.java). The application is used to illustrate tasks involved in packaging, deploying, configuring, and running an application that contains web components. The section Chapter 2, Using the Tutorial Examples explains how to get the code for the example. The source code for the example is in the tut-install/examples/web/hello2/ directory.

Web Modules

In the Java EE architecture, web components and static web content files such as images are called web resources. A web module is the smallest deployable and usable unit of web resources. A Java EE web module corresponds to a web application as defined in the Java Servlet specification.

In addition to web components and web resources, a web module can contain other files:

A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where XHTML pages, client-side classes and archives, and static web resources, such as images, are stored.

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

If your web module does not contain any servlets, filter, or listener components then it does not need a web application deployment descriptor. In other words, if your web module only contains XHTML pages and static files, you are not required to include a web.xml file.

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

A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a web archive (WAR) file. Because the contents and use of WAR files differ from those of JAR files, WAR file names use a .war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet Specification.

To deploy a WAR on the Enterprise Server, the file must also contain a runtime deployment descriptor. The runtime deployment descriptor is an XML file that contains information such as the context root of the web application and the mapping of the portable names of an application’s resources to the Enterprise Server’s resources. The Enterprise Server web application runtime DD is named sun-web.xml and is located in the WEB-INF directory along with the web application DD. The structure of a web module that can be deployed on the Enterprise Server is shown in Figure 3–4.

Figure 3–4 Web Module Structure

Diagram of web module structure. WEB-INF and web pages
are under the root. Under WEB-INF are descriptors and the lib, classes, and
tags directories.

Packaging Web Modules

A web module must be packaged into a WAR in certain deployment scenarios and whenever you want to distribute the web module. You package a web module into a WAR by executing the jar command in a directory laid out in the format of a web module, by using the Ant utility, or by using the IDE tool of your choice. This tutorial shows you how to use NetBeans IDE or Ant to build, package, and deploy the sample applications.

    To build the hello2 application with NetBeans IDE, follow these instructions:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to:


    tut-install/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 build the hello2 application using the Ant utility, follow these steps:

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

  2. Type ant. This command will spawn any necessary compilations, copy files to the tut-install/examples/web/hello2/build/ directory, create the WAR file, and copy it to the tut-install/examples/web/hello2/dist/ directory.

Deploying a WAR File

You can deploy a WAR file to the Enterprise Server in a few ways:

All these methods are described briefly in this chapter; however, throughout the tutorial, you will use ant and NetBeans IDE for packaging and deploying.

Setting the Context Root

A context root identifies a web application in a Java EE server. You specify the context root when you deploy a web module. A context root must start with a forward slash (/) and end with a string.

In a packaged web module for deployment on the Enterprise Server, the context root is stored in sun-web.xml.

    To edit the context root, do the following:

  1. Expand your project tree in the Projects pane of NetBeans IDE.

  2. Expand the Web Pages and WEB-INF nodes of your project.

  3. Double-click sun-web.xml.

  4. In the editor pane, click Edit As XML.

  5. Edit the context root, which is enclosed by the context-root element.

Deploying a Packaged Web Module

If you have deployed the hello2 application, before proceeding with this section, undeploy the application by following one of the procedures described in Undeploying Web Modules.

Deploying with the Admin Console

  1. Expand the Applications node.

  2. Click the Deploy button.

  3. Select the radio button labeled “Package file to be uploaded to the Application Server.”

  4. Type the full path to the WAR file (or click on Browse to find it), and then click the OK button.

  5. Click Next.

  6. Type the application name.

  7. Type the context root.

  8. Select the Enabled box.

  9. Click the Finish button.

Deploying with asadmin

To deploy a WAR with asadmin, open a terminal window or command prompt and execute


asadmin deploy full-path-to-war-file

Deploying with Ant

To deploy a WAR with the Ant tool, open a terminal window or command prompt in the directory where you built and packaged the WAR, and execute


ant deploy

Deploying with NetBeans IDE

    To deploy a WAR with NetBeans IDE, do the following:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to your project and open it.

  3. In the Projects tab, right-click the project and select Deploy.

Testing Deployed Web Modules

Now that the web module is deployed, you can view it by opening the application in a web browser. By default, the application is deployed to host localhost on port 8080. The context root of the web application is hello2.

    To test the application, follow these steps:

  1. Open a web browser.

  2. Enter the following URL in the web address box:


    http://localhost:8080/hello2
  3. Enter your name, and click Submit.

The application should display the name you submitted.

Listing Deployed Web Modules

The Enterprise Server provides two ways to view the deployed web modules: the Admin Console and the asadmin command.

    To use the Admin Console:

  1. Open the URL http://localhost:4848/ in a browser.

  2. Expand the Applications node.

Use the asadmin command as follows:


asadmin list-components

Updating Web Modules

    A typical iterative development cycle involves deploying a web module and then making changes to the application components. To update a deployed web module, you must do the following:

  1. Recompile any modified classes.

  2. If you have deployed a packaged web module, update any modified components in the WAR.

  3. Redeploy the module.

  4. Reload the URL in the client.

Dynamic Reloading

If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed pages or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/context-root. The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes.

This capability is useful in a development environment, because it allows code changes to be tested quickly. Dynamic reloading is not recommended for a production environment, however, because it may degrade performance. In addition, whenever a reload is done, the sessions at that time become invalid and the client must restart the session.

    To enable dynamic reloading, use the Admin Console:

  1. Select the Applications Server node.

  2. Select the Advanced tab.

  3. Check the Reload Enabled box to enable dynamic reloading.

  4. Enter a number of seconds in the Reload Poll Interval field to set the interval at which applications and modules are checked for code changes and dynamically reloaded.

  5. Click the Save button.

    In addition, to load new servlet files, do the following:

  1. Create an empty file named .reload at the root of the module:


    domain-dir/applications/context-root/.reload
  2. Explicitly update the .reload file’s time stamp each time you make these changes. On UNIX, execute


    touch .reload
    

Undeploying Web Modules

You can undeploy web modules in four ways: you can use NetBeans IDE, the Admin Console, the asadmin command, or the Ant tool.

    To use NetBeans IDE:

  1. Ensure the Enterprise Server is running.

  2. In the Services window, expand the Servers node, Enterprise Server instance and the Applications node.

  3. Right-click the application or module and choose Undeploy.

    To use the Admin Console:

  1. Open the URL http://localhost:4848/ in a browser.

  2. Expand the Applications node.

  3. Select the check box next to the module you wish to undeploy.

  4. Click the Undeploy button.

Use the asadmin command as follows:


asadmin undeploy context-root

To use the Ant tool, execute the following command in the directory where you built and packaged the WAR:


ant undeploy

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.

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).

    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/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/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/examples/web/hello2/.

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

To deploy the example using NetBeans IDE, right-click on the project in the Projects pane and select 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 XHTML 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 Enterprise Server will use a file named index.xhtml as the default welcome file. If there is no welcome file and no file named index.xhtml, the Enterprise Server returns a directory listing.

Setting Initialization Parameters

The web components in a web module share an object that represents their application 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:

    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:

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 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:

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.

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.

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 20, Running the Persistence Examples describes how web applications use annotations supported by the Java Persistence API. Chapter 25, Getting Started 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.

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 20, Running the Persistence Examples 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;

Further Information about Web Applications

For more information on web applications, see: