Note: When learning to use the selvert filter to process Chinese garbled characters, UTF-8 is used to process Chinese garbled Characters During filter configuration initialization, while gbk is used in the submitted jsp page. Although the two types can contain Chinese garbled characters, the format of garbled characters is inconsistent. Therefore, an error occurred while compiling.
Solution: UTF-8 or gbk is used everywhere.
// Filter class
CharactorFilter. jsp
Package cn.com. Filter;
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 class CharactorFilter implements Filter {// inherits the Filter class
// Character encoding
String encoding = null;
Public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
If (encoding! = Null ){
// Set the request character encoding
Request. setCharacterEncoding (encoding );
// Set the response character encoding
Response. setContentType ("text/html; charset =" + encoding );
}
// Pass it to the next Filter
Chain. doFilter (request, response );
}
Public void init (FilterConfig filterConfig) throws ServletException {
// Obtain initialization parameters
Encoding = filterConfig. getInitParameter ("encoding ");
}
Public void destroy (){
// TODO Auto-generated method stub
Encoding = null;
}
}
Web. xml
<Filter> <! -- Note that this is filter. do not configure it as servlet -->
<Filter-name> CharactorFilter </filter-name> <! -- Filter Name -->
<Filter-class> cn.com. Filter. CharactorFilter </filter-class> <! -- Complete filter class name -->
<Init-param> <! -- Initialize parameters -->
<Param-name> encoding </param-name> <! -- Parameter name -->
<Param-value> UTF-8 </param-value> <! -- Parameter value -->
</Init-param>
</Filter>
<Filter-mapping> <! -- Filter ing -->
<Filter-name> CharactorFilter </filter-name> <! -- Filter Name -->
<Url-pattern>/* </url-pattern> <! -- URL ing to handle garbled code for all pages -->
</Filter-mapping>