Filter is an advanced feature in the servlet specification, and unlike Servlets, they do not process client requests and are only used to modify request,response; If you want to implement a custom filter yourself must implement the Javax.servlet.Filter interface, there are three methods in the interface:
Package javax.servlet; Import java.io.IOException; /** * A Filter is an object, performs filtering tasks on either the * request to A resource (A servlet or static conte NT), or on the response * from a resource, or both. * @since Servlet 2.3 */public interface Filter {/** * Called by the Web container to indicate to a filter that I T is * being placed into service. */public void init (Filterconfig filterconfig) throws servletexception; /** * The <code> dofilter</code> method of the Filter is called by the * container each time a request /response pair is passed through the "chain due to a" client request for a resource at the end of the chain. * The Filterchain passed in to this method allows the Filter to pass * on the request and response to the next entity In the chain. */public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) Throws IoexceptioN, Servletexception; /** * Called by the Web container to indicate to a filter that it's being * taken out of service. */public void Destroy (); }
Three methods reflect the life cycle of the filter, where the init (), Destory () method is called only when the Web program is loaded or unloaded, and the DoFilter () method is called every time the request is made. In addition, the simple configuration of filter in Web. XML is as follows:
<!--Char Encoding--<filter > < filter-name> characterfilter </filter-name > < filter-class> space.ifei.wxchat.sys.CharacterFilter </filter-class ><!-- <async-supported> true</async-supported>--><!-- <init-param>--><!-- <param-name>xxx</ param-name>--><!-- <param-value>QQQ</param-value>--><!-- </init-param > </filter > <filter-mapping > <filter-name> characterfilter </ Filter-name > <!--the same filter,filter name must be the same-- <url-pattern>/* </url-pattern > <!-- Filter valid URL rules, you can use wildcard characters--><!-- <dispatcher>REQUEST</dispatcher>--><!-- < Dispatcher>forward</dispatcher>--
Where: "async-supported" set the servlet to open asynchronous support, default does not open, see details: http://www.ibm.com/developerworks/cn/java/j-lo-servlet30/" Init-param "Sets the value of the property inside the custom filter, and the dispatcher setting reaches the servlet in 4 ways: Request,forward,include,error. It is important to note that multiple Filter,filter can be configured in one Web program in order of execution
Filter in Java--the basic article