The code is as follows:
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;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Setcharacterencodingfilter implements filter {//To implement filter interface//store encoded format information private String encode = null; public void Destroy () {} public void Dofilter (ServletRequest req,servletresponse resp,filterchain chain) throws
ioexception,servletexception{//Conversion HttpServletRequest request = (httpservletrequest) req;
HttpServletResponse response = (httpservletresponse) resp; * * To determine if the encoded format is configured in the Web.xml file * If empty, set the encoding format to the encoding format in the configuration file * Otherwise the encoding format is set to GBK/if (This.encode!= null &&
!this.encode.equals ("")) {request.setcharacterencoding (This.encode);
Response.setcharacterencoding (This.encode); }else{Request.setCharacterencoding ("GBK");
Response.setcharacterencoding ("GBK");
* * * Use the next filter or target resource (servlet or JSP page) in the Dofilter method call chain.
* Chain.dofilter processes the remainder of the filter (if any), and ultimately processes the requested servlet or JSP page.
* * Chain.dofilter (request, response); public void init (Filterconfig config) throws servletexception{//Get information about the encoding format configured in Web.xml file This.encode = config.ge
Tinitparameter ("encode"); }
}
The configuration information in the Web.xml file is as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns= "http://java.sun.com/xml/ns/j2ee" xmlns:xsi= "http://" Www.w3.org/2001/XMLSchema-instance "version=" 2.4 "xsi:schemalocation=" http://java.sun.com/xml/ns/j2ee http:// Java.sun.com/xml/ns/j2ee/web-app_2_4.xsd > <!--filter configuration information--> <filter> <filter-name> Setcharacterencodingfilter</filter-name> <!--filter settings encoding file--> <filter-class> ssh.dlc.chp1.filter.Se
Tcharacterencodingfilter </filter-class> <init-param> <!--init-param element defines the initialization parameters of the filter --> <description> set name and encoding type for parameters and values </description> <param-name>encode</param-name> <PA ram-value>gbk</param-value> </init-param> </filter> <filter-mapping> <!--filter-m
Apping tells the container that all requests matching the pattern should be allowed through the access control filter. All access to the. Do end filter--> <filter-name>SetCharacterEncodingFilter</filter-name> <url-pattern& via filter file first Gt;*.do</url-pAttern> </filter-mapping> </web-app>