Chaining Filters

 < Free Open Study > 

The Logger and XSLTFilter filters can be chained together by including both in web.xml:

    <?xml version="1.0" encoding="ISO-8859-1"?>    <!DOCTYPE web-app      PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"      "">    <web-app>      <filter>        <filter-name>Logger</filter-name>        <filter-class>filters.LoggerFilter</filter-class>      </filter>      <filter>        <filter-name>XSLTFilter</filter-name>        <filter-class>filters.SmartXSLFilter</filter-class>        <init-param>          <param-name>xsltfile</param-name>          <param-value>/xsl/stockquotes.xsl</param-value>        </init-param>      </filter>      <filter-mapping>         <filter-name>Logger</filter-name>         <url-pattern>/*</url-pattern>      </filter-mapping>      <filter-mapping>        <filter-name>XSLTFilter</filter-name>        <servlet-name>XMLOutServlet</servlet-name>      </filter-mapping>      <servlet>        <servlet-name>XMLOutServlet</servlet-name>        <servlet-class>filters.XMLOutServlet</servlet-class>      </servlet>    </web-app> 

Restart Tomcat, and try accessing XMLOutServlet using both Internet Explorer and Netscape once more. The XSLTFilter will work as before. Now check out the log file in the logs directory of Tomcat and you will see that each and every access to XMLOutServlet is logged by the Logger filter. The two filters have been chained together.

The log entry from the Logger filter always precedes the entry from the XSLTFilter, which indicates that the Logger filter is always upstream. This behavior is defined in the Servlet 2.3 specification: all filters with <filter-mapping> elements that use <url-pattern> elements are chained (in the order that they appear in the web.xml file) before the <filter-mapping> elements that use <servlet-name> elements (again in the order that they appear in the web.xml file).

Designing Filters

To round of the chapter, I'll mention a few guidelines that you should keep in mind when you're developing filters:

  • Filters should be designed to be easily configurable at deployment time. Often, a filter can be reused through the careful planning and use of initialization parameters.

  • Filtering logic, unlike that of servlets, should not depend on session state information that is maintained between requests because a single filter instance may be servicing many different requests at the same time.

  • When mapping filters, always use the most restrictive mapping possible - use <servletname> instead of <url-pattern> if possible. The overhead of filter operations can be significantly increased if the filter is consistently applied to web resources that don't need it.

 < Free Open Study > 

Professional Java Servlets 2.3
Professional Java Servlets 2.3
ISBN: 186100561X
EAN: 2147483647
Year: 2006
Pages: 130 © 2008-2017.
If you may any questions please contact us: