这样比你自己在Servlet代码中硬编码request.setCharacterEncoding, response.setCharacterEncoding方便多了
总之,如果你添加了这个filter,配置好了web.xml,那么如果还出现乱码问题,你就去检查你的JSP和HTML代码中的encoding选项吧(charset, pageEncoding, meta.content之类的),看看是否和你在web.xml中配置的filter的encoding相匹配
CharacterEncodingFilter.java
1 public class CharacterEncodingFilter implements Filter { 2 protected String encoding = null; 3 protected FilterConfig filterConfig = null; 4 protected boolean enable = false; 5 public void destroy() { 6 this.encoding = null; 7 this.filterConfig = null; 8 } 9 public void doFilter(ServletRequest request, ServletResponse response, 10 FilterChain chain) throws IOException, ServletException { 11 if (this.enable) { 12 String encoding = selectEncoding(request); 13 if (encoding != null && !encoding.equals("")) { 14 System.out.println(this + ": ignore = true " + encoding); 15 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(). 16 response.setCharacterEncoding(encoding); 17 } 18 } 19 // Pass control on to the next filter 20 chain.doFilter(request, response); 21 } 22 public void init(FilterConfig filterConfig) throws ServletException { 23 this.filterConfig = filterConfig; 24 this.encoding = filterConfig.getInitParameter("encoding"); 25 // 26 String enable = filterConfig.getInitParameter("enable"); 27 if (enable.equalsIgnoreCase("true")) { 28 this.enable = true; 29 } else { 30 this.enable = false; 31 } 32 } 33 protected String selectEncoding(ServletRequest request) { 34 return (this.encoding); 35 } 36 }
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>