The filter in the servlet is a server-side program that implements the Javax.servlet.Filter interface, the main purpose of which is to filter character encoding, make some business logic judgments, and so on. The principle is that as long as you configure the Web. xml file to intercept the client request, it will help you intercept the request, at this time you can set the request or response (requests, Response) unified encoding, simplify the operation, but also to make logical judgments, such as whether the user has logged on, There is no permission to access the page and so on work. It starts with your web app, initializes it once, and intercepts the request later, only when your web app is stopped or redeployed, and the following filter code samples are used to understand its use: AOP role
PackageCom.hello.web.listener; Importjava.io.IOException; Importjavax.servlet.*; Importjavax.servlet.http.HttpServletRequest; ImportJavax.servlet.http.HttpServletResponse; //Main Purpose: Filter character coding; second, do some application logic judgment and so on. //filter starts with the web App//filter is also destroyed when the Web app is restarted or destroyed Public classMycharsetfilterImplementsFilter {PrivateFilterconfig config =NULL; Public voiddestroy () {System.out.println ("Mycharsetfilter Ready to destroy ..."); } Public voidDoFilter (ServletRequest arg0, servletresponse arg1,filterchain chain)throwsIOException, servletexception {//Forcing type conversionsHttpServletRequest request =(httpservletrequest) arg0; HttpServletResponse Response=(HttpServletResponse) arg1; //gets the encoding set for the WEB.XM set, set to request, responseRequest.setcharacterencoding (Config.getinitparameter ("CharSet")); Response.setcontenttype (Config.getinitparameter ("ContentType")); Response.setcharacterencoding (Config.getinitparameter ("CharSet")); //forward a request to a destinationChain.dofilter (request, response); } Public voidInit (Filterconfig arg0)throwsservletexception { This. config =arg0; System.out.println ("Mycharsetfilter initialization ..."); } }
The following is Mycharsetfilter.java configured in Web. XML:
<Filter> <Filter-name>Filter</Filter-name> <Filter-class>Dc.gz.filters.MyCharsetFilter</Filter-class> <Init-param> <Param-name>CharSet</Param-name> <Param-value>UTF-8</Param-value> </Init-param> <Init-param> <Param-name>ContentType</Param-name> <Param-value>Text/html;charset=utf-8</Param-value> </Init-param> </Filter> <filter-mapping> <Filter-name>Filter</Filter-name> <!--* represents interception of all requests or specified requests/test.do/xxx.do - <Url-pattern>/*</Url-pattern> </filter-mapping>
The above example simply explains the use of the filter, specific other applications can see the specific scene.
The role of filter in Web. xml