What is a filter, and how does it work
by, 01-01-2012 at 04:57 PM (2769 Views)
Responses and requests are intercepted dynamically by a filter so that to transform the information present in responses of requests. However, responses are not typically created by them. For transformation of the response from JSP or Servlet filters are used before it is sent back to client. Reusability gets improved by the filters by placement of the recurring tasks as a reusable unit in the filter.
Better way of thinking servlet filters is to consider steps whose response is sent before a JSP, Static resource (like web application’s HTML, or servlet) is reached.
The filters can be used for caching & compressing content, image conversions (scaling up/down), logging & auditing, authenticating incoming requests, localization of the request and the response, XSL transformation of XML content, site hit count etc. The configuration of the filters is done via web.xml file, as following:
XML Code: This is the web.xml file for filter configuration<web-app> <filter> <filter-name>HitCounterFilter</filter-name> <filter-class>myPkg.HitCounterFilter</filter-class> </filter> <filter-mapping> <filter-name>HitCounterFilter</filter-name> <url-pattern>/usersection/*</url-pattern> </filter-mapping> ... </web-app>