[ Team LiB ] Previous Section Next Section

Recipe 19.2 Mapping a Filter to a JSP


You want to have the web container apply a filter to requests for a certain JSP page.


Use the url-pattern child element of the filter-mapping element in the deployment descriptor to map the filter to the JSP.


Map a filter to a JSP by specifying the path to the JSP page using the filter-mapping element's url-pattern subelement. Example 19-3 shows a web.xml configuration that maps the filter in Example 19-2 to the requestHeaders.jsp.

Example 19-3. Mapping a filter to a JSP
<!-- top of web.xml deployment descriptor -->



<!-- rest of deployment descriptor -->

You can create a number of filter mappings for a single filter, each with their own type of URL pattern.

With the configuration of Example 19-3, any requests for /displayHeaders.jsp will pass through the filter named LogFilter. Example 19-2 shows the source code for the LogFilter class. The code logs a message about the request, before the request is passed along the filter chain to the JSP. The logged message looks like:

INFO - Request received from: localhost for: http://localhost:8080/home/

The JSP itself does not have to be configured in a special way for the filter to be applied to it. You can apply the filter to all JSPs with this configuration:


The URL pattern *.jsp is an extension mapping that associates the LogFilter with any of the web application's components that end with .jsp.

See Also

Recipe 7.9 on using a filter to read request parameter values; Recipe 11.11 on using a filter to monitor session attributes; Recipe 18.3 on using a filter to alter then forward the request; Recipe 19.3 on mapping more than one filter to a servlet; Recipe 19.4 on changing the order filters are applied to a servlet; Recipe 19.5 on configuring filter initialization parameters; Recipe 19.6 on blocking requests; Recipe 19.7 on filtering the HttpServletResponse; Recipe 19.8 on using filters with RequestDispatchers; Recipe 19.9 on using filters to check request parameters; Recipe 19.10 on using filters to disallow requests from certain IP addresses.

    [ Team LiB ] Previous Section Next Section