Recipe 19.2 Mapping a Filter to a JSP


Problem

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

Solution

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

Discussion

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 --> <filter>     <filter-name>LogFilter</filter-name>     <filter-class>com.jspservletcookbook.LogFilter</filter-class> </filter> <filter-mapping>     <filter-name>LogFilter</filter-name>     <url-pattern>/displayHeaders.jsp</url-pattern> </filter-mapping> <!-- 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/ displayHeaders.jsp 

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:

 <filter-mapping>     <filter-name>LogFilter</filter-name>     <url-pattern>*.jsp</url-pattern> </filter-mapping> 

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.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net