tomcat乱码主要是http post/get的请求参数,在tomcat接收后内部无法正确进行解码。
这个问题跟两个因素有关系:
1. http get/post 采用的字符集
2. 启动tomcat 的jvm运行的字符集
要想解决中文乱码问题,必须对这两个因素十分清楚。
解决思路:
前提(web应用的代码中不能进行特殊的字符集编码、解码操作)
web服务器端:服务器端jvm启动时,常用的linux/unix的字符编码为utf8或者GBK(LANG环境变量的设定),你选用的哪一种,自己必须清楚。(在服务器端,我一直采用utf8,数据库也是utf8)
如果服务端是utf8编码,那么中文乱码将取决于http get/post采用的字符集。如果字符集不匹配,那么必须进行编码转换。转换的方法是做一个filter。
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.xxx.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value> <!--此处的字符集为http request的缺省字符集, 如果http header指定了字符集,将忽略此设定-->
</init-param>
</filter>
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
logger.debug("http request encoding is:" + request.getCharacterEncoding());
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding); // init-param参数设定的值
}