这样比你自己在Servlet代码中硬编码request.setCharacterEncoding, response.setCharacterEncoding方便多了
总之,如果你添加了这个filter,配置好了web.xml,那么如果还出现乱码问题,你就去检查你的JSP和HTML代码中的encoding选项吧(charset, pageEncoding, meta.content之类的),看看是否和你在web.xml中配置的filter的encoding相匹配
CharacterEncodingFilter.java
public class CharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean enable = false;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (this.enable) {
String encoding = selectEncoding(request);
if (encoding != null && !encoding.equals("")) {
System.out.println(this + ": ignore = true " + encoding);
request.setCharacterEncoding(encoding); //Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().
response.setCharacterEncoding(encoding);
}
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
//
String enable = filterConfig.getInitParameter("enable");
if (enable.equalsIgnoreCase("true")) {
this.enable = true;
} else {
this.enable = false;
}
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
web.xml
<filter>
<filter-name>charset-encoding</filter-name>
<filter-class>cn.mldn.lxh.encoding.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>enable</param-name>
<param-value>true</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>charset-encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>