The Java EE 6 Tutorial

Configuring Web Applications: The hello2 Example

Web applications are configured by means of annotations or by 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. Examples demonstrate procedures for configuring the Hello, World application.

Mapping URLs to Web Components

When it receives a request, the web container must determine which web component should handle the request. The web container 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, optionally, a URL pattern:


http://host:port/context-root[/url-pattern]

You set the URL pattern for a servlet by using the @WebServlet annotation in the servlet source file. For example, the GreetingServlet.java file in the hello2 application contains the following annotation, specifying the URL pattern as /greeting:

@WebServlet("/greeting")
public class GreetingServlet extends HttpServlet {
    ...

This annotation indicates that the URL pattern /greeting follows the context root. Therefore, when the servlet is deployed locally, it is accessed with the following URL:


http://localhost:8080/hello2/greeting

To access the servlet by using only the context root, specify "/" as the URL pattern.

Examining the hello2 Web Module

The hello2 application behaves almost identically to the hello1 application, but it is implemented using Java Servlet technology instead of JavaServer Faces technology. You can use a text editor to view the application files, or you can use NetBeans IDE.

ProcedureTo View the hello2 Web Module Using NetBeans IDE

  1. In NetBeans IDE, 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. Expand the Source Packages node, then the servlets node.

  6. Double-click the GreetingServlet.java file to view it.

    This servlet overrides the doGet method, implementing the GET method of HTTP. The servlet displays a simple HTML greeting form whose Submit button, like that of hello1, specifies a response page for its action. The following excerpt begins with the @WebServlet annotation that specifies the URL pattern, relative to the context root:

    @WebServlet("/greeting")
    public class GreetingServlet extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            response.setBufferSize(8192);
            PrintWriter out = response.getWriter();
    
            // then write the data of the response
            out.println("<html>"
                    + "<head><title>Servlet Hello</title></head>");
    
            // then write the data of the response
            out.println("<body  bgcolor=\"#ffffff\">"
                    + "<img src=\"duke.waving.gif\" alt=\"Duke waving\">"
                    + "<h2>Hello, my name is Duke. What's yours?</h2>"
                    + "<form method=\"get\">"
                    + "<input type=\"text\" name=\"username\" size=\"25\">"
                    + "<p></p>"
                    + "<input type=\"submit\" value=\"Submit\">"
                    + "<input type=\"reset\" value=\"Reset\">"
                    + "</form>");
    
            String username = request.getParameter("username");
            if (username != null && username.length() > 0) {
                RequestDispatcher dispatcher =
                        getServletContext().getRequestDispatcher("/response");
    
                if (dispatcher != null) {
                    dispatcher.include(request, response);
                }
            }
            out.println("</body></html>");
            out.close();
        }
        ...
  7. Double-click the ResponseServlet.java file to view it.

    This servlet also overrides the doGet method, displaying only the response. The following excerpt begins with the @WebServlet annotation, which specifies the URL pattern, relative to the context root:

    @WebServlet("/response")
    public class ResponseServlet extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            PrintWriter out = response.getWriter();
    
            // then write the data of the response
            String username = request.getParameter("username");
            if (username != null && username.length() > 0) {
                out.println("<h2>Hello, " + username + "!</h2>");
            }
        }
        ...
  8. Under the Web Pages node, expand the WEB-INF node and double-click the sun-web.xml file to view it.

    In the General tab, observe that the Context Root field is set to /hello2.

    For this simple servlet application, a web.xml file is not required.

Building, Packaging, Deploying, and Running the hello2 Example

You can use either NetBeans IDE or Ant to build, package, deploy, and run the hello2 example.

ProcedureTo Build, Package, Deploy, and Run the hello2 Example Using NetBeans IDE

  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.

  7. Right-click the project and select Deploy.

  8. In a web browser, open the URL http://localhost:8080/hello2/greeting.

    The URL specifies the context root, followed by the URL pattern.

    The application looks much like the hello1 application shown in Figure 3–2. The major difference is that after you click the Submit button, the response appears below the greeting, not on a separate page.

ProcedureTo Build, Package, Deploy, and Run the hello2 Example Using Ant

  1. In a terminal window, go to:


    tut-install/examples/web/hello2/
    
  2. Type the following command:


    ant
    

    This target builds the WAR file and copies it to the tut-install/examples/web/hello2/dist/ directory.

  3. Type ant deploy.

    Ignore the URL shown in the deploy target output.

  4. In a web browser, open the URL http://localhost:8080/hello2/greeting.

    The URL specifies the context root, followed by the URL pattern.

    The application looks much like the hello1 application shown in Figure 3–2. The major difference is that after you click the Submit button, the response appears below the greeting, not on a separate page.

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 that 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 that matches in the WAR.

If no welcome file is specified, the GlassFish Server will use a file named index.html as the default welcome file. If there is no welcome file and no file named index.html, the GlassFish Server returns a directory listing.

By convention, you specify the welcome file for a JavaServer Faces application as faces/file-name.xhtml.

Setting Context and 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.

ProcedureTo Add a Context Parameter Using NetBeans IDE

  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. Expand the Context Parameters node.

  7. Click Add.

    An Add Context Parameter dialog opens.

  8. In the Parameter Name field, type the name that specifies the context object.

  9. In the Parameter Value field, type the parameter to pass to the context object.

  10. Click OK.

ProcedureTo Add an Initialization Parameter Using NetBeans IDE

You can use the @WebServlet annotation to specify web component initialization parameters by using the initParams attribute and the @WebInitParam annotation. For example:


@WebServlet(urlPatterns="/MyPattern", initParams=
  {@WebInitParam(name="ccc", value="333")})

Alternatively, you can add an initialization parameter to the web.xml file. To do this using NetBeans IDE, follow these steps.

  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. Click the Add button under the Initialization Parameters table.

    An Add Initialization Parameter dialog opens.

  7. In the Parameter Name field, type the name of the parameter.

  8. In the Parameter Value Field, type the parameter’s value.

  9. Click OK.

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.

You can have multiple error-page elements in your deployment descriptor. Each element 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.

ProcedureTo Set Up Error Mapping Using NetBeans IDE

  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.

    The Add Error Page dialog opens.

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

  9. In the Error Code field, type the HTTP status code that will cause the error page to be opened.

  10. In the Exception Type field, type the exception that will cause the error page to load.

  11. Click OK.

Declaring Resource References

If your web component uses such objects 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 on using it in web applications. First, you can inject resources only into container-managed objects, since 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 such objects 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 explains how to use a couple of the annotations supported by a servlet container to inject resources. Chapter 21, Running the Persistence Examples, explains how web applications use annotations supported by the Java Persistence API. Chapter 25, Getting Started Securing Web Applications, explains 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, a method, or a 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’s 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 21, 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;