The Java EE 6 Tutorial

Specifying Filter Mappings

A web container uses filter mappings to decide how to apply filters to web resources. A filter mapping matches a filter to a web component by name or to web resources by URL pattern. The filters are invoked in the order in which filter mappings appear in the filter mapping list of a WAR. You specify a filter mapping list for a WAR in its deployment descriptor by either using NetBeans IDE or coding the list by hand with XML.

If you want to log every request to a web application, you map the hit counter filter to the URL pattern /*.

You can map a filter to one or more web resources, and you can map more than one filter to a web resource. This is illustrated in Figure 10–1, where filter F1 is mapped to servlets S1, S2, and S3; filter F2 is mapped to servlet S2; and filter F3 is mapped to servlets S1 and S2.

Figure 10–1 Filter-to-Servlet Mapping

Diagram of filter-to-servlet mapping with filters F1-F3
and servlets S1-S3. F1 filters S1-S3, then F2 filters S2, then F3 filters
S1 and S2.

Recall that a filter chain is one of the objects passed to the doFilter method of a filter. This chain is formed indirectly by means of filter mappings. The order of the filters in the chain is the same as the order in which filter mappings appear in the web application deployment descriptor.

When a filter is mapped to servlet S1, the web container invokes the doFilter method of F1. The doFilter method of each filter in S1’s filter chain is invoked by the preceding filter in the chain by means of the chain.doFilter method. Because S1’s filter chain contains filters F1 and F3, F1’s call to chain.doFilter invokes the doFilter method of filter F3. When F3’s doFilter method completes, control returns to F1’s doFilter method.

ProcedureTo Specify Filter Mappings Using NetBeans IDE

  1. Expand the application’s project node in the Project pane.

  2. Expand the Web Pages and WEB-INF nodes under the project node.

  3. Double-click web.xml.

  4. Click Filters at the top of the editor pane.

  5. Expand the Servlet Filters node in the editor pane.

  6. Click Add Filter Element to map the filter to a web resource by name or by URL pattern.

  7. In the Add Servlet Filter dialog, enter the name of the filter in the Filter Name field.

  8. Click Browse to locate the servlet class to which the filter applies.

    You can include wildcard characters so that you can apply the filter to more than one servlet.

  9. Click OK.

  10. To constrain how the filter is applied to requests, follow these steps.

    1. Expand the Filter Mappings node.

    2. Select the filter from the list of filters.

    3. Click Add.

    4. In the Add Filter Mapping dialog, select one of the following dispatcher types:

      You can direct the filter to be applied to any combination of the preceding situations by selecting multiple dispatcher types. If no types are specified, the default option is REQUEST.