It's an object that can intercept and change requests or responses in a web application. For example, a servlet can generate a response and a filter can add http directives to it.
A filter is simply a class that implements the interface Filter and is configured into the web.xml:
<filter> <filter-name>cacheFilter</filter-name> <filter-class>org.davis.filter.CacheFilter</filter-class> </filter> <filter-mapping> <filter-name>cacheFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
The above configuration can be replaced by an annotation into the filter itself:
@WebFilter("/*")
To automatically generate a filter in Eclipse, select File->Other, then "filter" and follow the wizard. This is the output:
import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * Servlet Filter implementation class MyFilter */ public class MyFilter implements Filter { /** * Default constructor. */ public MyFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here // pass the request along the filter chain chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
Common uses of filters are: checking if the user is logged-in, logging, data compression, data conversion etc.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.