The role of 1.java coded filters:
Java filters can intercept requests and responses from target resources, and the filtering information executes more than Servlets.
Its newly added features include:
1. Application life cycle event control;
2. New Internationalization;
3. Clarification of the loading rules of the class;
4. New error and security attributes;
5. Does not endorse the use of the httputils category;
6. A variety of useful methods;
7. Clarified and expanded several servlet DTDs;
8. Filter function.
Use of 2.java filters:
(1) write a generic Java class that implements the filter interface
Import Java.io.ioexception;import Javax.servlet.filter;import javax.servlet.filterchain;import Javax.servlet.filterconfig;import Javax.servlet.servletexception;import Javax.servlet.servletrequest;import Javax.servlet.ServletResponse; Public classEcodefilter implements Filter {//define encoding By default is empty PrivateString encoding =NULL; Public voiddestroy () {}//Automatic Call filtering method DoFilter Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain) throws IOException, Servlet Exception {//filter the data in the request if the encoding is not empty if(Encoding! =NULL) { //set the request character encodingrequest.setcharacterencoding (encoding); //Set Response character encodingResponse.setcontenttype ("text/html;charset="+encoding); } //Pass to next filter or next servlet/jspChain.dofilter (request, response); } Public voidinit (filterconfig config) throws servletexception {//The configuration code of the filter in Web. XML is removed to assign the value to encodingEncoding=config.getinitparameter ("encoding"); }}
(2) Configuring filters in WEB.XM
<!--encoding filter, filter for all addresses-- <filter> <filter-name>encodefilter Filter Name </filter-name > <filter-class>com.bw.shop.util.ecodefilter Filter's fully qualified name </filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</ param-value> </init-param> </filter> <filter-mapping> <filter-name >encodefilter Filter Name </filter-name> <url-pattern>/* page address to be filtered </ url-pattern> </filter-mapping>
Java Encoding Filter