在用到tomcat或者其他的容器的时候,经常碰到乱码。并不是页面的问题,在serlet接受页面的post的时候(如果页面没有设置编码,默认编码是iso8859-1,如果设置了编码,和容器做数据交换的时候,也容易出现乱码),乱码就已经接收过来了,在servlet里面去做的其他的处理都是不明智的,这里介绍个过滤器解决乱码的方案。欢迎交流。
在tomcat5.028,5.512,在weblogic8.1上测试通过。
源代码如下:
public class Charset implements Filter {
private String encoding="gb2312";
public void init(FilterConfig filterConfig) throws ServletException {
String e=filterConfig.getInitParameter("encoding");
encoding=e==null?encoding:e;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
filterChain.doFilter(request,response);
}
public void destroy() {
// TODO Auto-generated method stub
}
}
在web.xml添加过滤器。
<filter>
<filter-name>Charset</filter-name>
<filter-class>comwiki.Charset</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Charset</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
ok,这样就ok了,赶紧测试吧!