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 Lifecycle

Web Modules: The hello1 Example

Examining the hello1 Web Module

To View the hello1 Web Module Using NetBeans IDE

Introduction to Scopes

Packaging a Web Module

To Set the Context Root

To Build and Package the hello1 Web Module Using NetBeans IDE

To Build and Package the hello1 Web Module Using Ant

Deploying a Web Module

To Deploy the hello1 Web Module Using NetBeans IDE

To Deploy the hello1 Web Module Using Ant

Running a Deployed Web Module

To Run a Deployed Web Module

Listing Deployed Web Modules

To List Deployed Web Modules Using the Administration Console

To List Deployed Web Modules Using the asadmin Command

Updating a Web Module

To Update a Deployed Web Module

Dynamic Reloading

To Disable or Modify Dynamic Reloading

Undeploying Web Modules

To Undeploy the hello1 Web Module Using NetBeans IDE

To Undeploy the hello1 Web Module Using Ant

Further Information about Web Applications

4.  JavaServer Faces Technology

5.  Introduction to Facelets

6.  Expression Language

7.  Using JavaServer Faces Technology in Web Pages

8.  Using Converters, Listeners, and Validators

9.  Developing with JavaServer Faces Technology

10.  JavaServer Faces Technology: Advanced Concepts

11.  Using Ajax with JavaServer Faces Technology

12.  Composite Components: Advanced Topics and Example

13.  Creating Custom UI Components and Other Custom Objects

14.  Configuring JavaServer Faces Applications

15.  Java Servlet Technology

16.  Uploading Files with Java Servlet Technology

17.  Internationalizing and Localizing Web Applications

Part III Web Services

18.  Introduction to Web Services

19.  Building Web Services with JAX-WS

20.  Building RESTful Web Services with JAX-RS

21.  JAX-RS: Advanced Topics and Example

Part IV Enterprise Beans

22.  Enterprise Beans

23.  Getting Started with Enterprise Beans

24.  Running the Enterprise Bean Examples

25.  A Message-Driven Bean Example

26.  Using the Embedded Enterprise Bean Container

27.  Using Asynchronous Method Invocation in Session Beans

Part V Contexts and Dependency Injection for the Java EE Platform

28.  Introduction to Contexts and Dependency Injection for the Java EE Platform

29.  Running the Basic Contexts and Dependency Injection Examples

30.  Contexts and Dependency Injection for the Java EE Platform: Advanced Topics

31.  Running the Advanced Contexts and Dependency Injection Examples

Part VI Persistence

32.  Introduction to the Java Persistence API

33.  Running the Persistence Examples

34.  The Java Persistence Query Language

35.  Using the Criteria API to Create Queries

36.  Creating and Using String-Based Criteria Queries

37.  Controlling Concurrent Access to Entity Data with Locking

38.  Using a Second-Level Cache with Java Persistence API Applications

Part VII Security

39.  Introduction to Security in the Java EE Platform

40.  Getting Started Securing Web Applications

41.  Getting Started Securing Enterprise Applications

42.  Java EE Security: Advanced Topics

Part VIII Java EE Supporting Technologies

43.  Introduction to Java EE Supporting Technologies

44.  Transactions

45.  Resources and Resource Adapters

46.  The Resource Adapter Example

47.  Java Message Service Concepts

48.  Java Message Service Examples

49.  Bean Validation: Advanced Topics

50.  Using Java EE Interceptors

Part IX Case Studies

51.  Duke's Bookstore Case Study Example

52.  Duke's Tutoring Case Study Example

53.  Duke's Forest Case Study Example

Index

 

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.

To View the hello2 Web Module Using NetBeans IDE

  1. From the File menu, choose 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 lang=\"en\">"
                    + "<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 his hand\">"
                + "<form method=\"get\">"
                + "<h2>Hello, my name is Duke. What's yours?</h2>"
                + "<input title=\"My name is: \"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 glassfish-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.

Running the hello2 Example

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

To Run the hello2 Example Using NetBeans IDE

  1. From the File menu, choose 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. The major difference is that after you click the Submit button, the response appears below the greeting, not on a separate page.

To 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. 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 Parameters

The web components in a web module share an object that represents their application context. You can pass context parameters to the context, or initialization parameters to a servlet. Context parameters are available to the entire web application. For information on initialization parameters, see Creating and Initializing a Servlet.

To Add a Context Parameter Using NetBeans IDE

These steps apply generally to web applications, but do not apply specifically to the examples in this chapter.

  1. Open the project.
  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.

    If the project does not have a web.xml file, follow the steps in To Create a web.xml File Using NetBeans IDE.

  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.

To Create a web.xml File Using NetBeans IDE

  1. From the File menu, choose New File.
  2. In the New File wizard, select the Web category, then select Standard Deployment Descriptor under File Types.
  3. Click Next.
  4. Click Finish.

    A basic web.xml file appears in web/WEB-INF/.

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.

To Set Up Error Mapping Using NetBeans IDE

These steps apply generally to web applications, but do not apply specifically to the examples in this chapter.

  1. Open the project.
  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.

    If the project does not have a web.xml file, follow the steps in To Create a web.xml File Using NetBeans IDE.

  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. Specify either an error code or an exception type:
    • To specify an error code, in the Error Code field, type the HTTP status code that will cause the error page to be opened, or leave the field blank to include all error codes.

    • To specify an exception type, in the Exception Type field, type the exception that will cause the error page to load. To specify all throwable errors and exceptions, type java.lang.Throwable.

  10. 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 and CDI 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 web container to inject resources. Chapter 33, Running the Persistence Examples, explains how web applications use annotations supported by the Java Persistence API. Chapter 40, Getting Started Securing Web Applications, explains how to use annotations to specify information about securing web applications. See Chapter 45, Resources and Resource Adapters for more information on resources.

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

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=javax.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 33, 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;