|[ Team LiB ]|
Recipe 19.2 Mapping a Filter to a 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.
<!-- 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 -->
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>
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 ]|