项目中遇到中文乱码的问题,过滤器也是正常的,找了很久发现问题。tomcat用的8.5的。
tomcat8.5以后版本, get请求方式,request对象使用的字符集默认为utf-8 , post请求方式,request对象使用的编码方式为ISO8859-1。
所以new String(str.getBytes("ISO-8859-1"), charset);出现本来是utf-8编码,用ISO-8859-1取导致乱码。
网上查了下,8.0貌似也是默认编码utf-8。
filter代码
package com.filter;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.filter.GetHttpServletRequestWrapper;
public class MyFilter implements Filter {
private String charset = "UTF-8";
private FilterConfig config;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//设置请求响应字符编码
request.setCharacterEncoding(charset);
response.setCharacterEncoding(charset);
//执行下一个过滤器(如果有的话,否则执行目标servlet)
HttpServletRequest req = (HttpServletRequest)request;
if(req.getMethod().equalsIgnoreCase("get"))
{
req = new GetHttpServletRequestWrapper(req);
}
chain.doFilter(req, response);
}
public void init(FilterConfig conf) throws ServletException {
this.config = conf;
String charset = config.getServletContext().getInitParameter("charset");
if( charset != null && charset.trim().length() != 0)
{
this.charset = charset;
}
}
}
tomcat8以后版本注释掉
if(req.getMethod().equalsIgnoreCase("get"))
{
req = new GetHttpServletRequestWrapper(req);
}
web.xml配置过滤器
<context-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</context-param>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
请求装饰类
package com.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class GetHttpServletRequestWrapper extends HttpServletRequestWrapper {
private String charset = "UTF-8";
public GetHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
/**
* 获得被装饰对象的引用和采用的字符编码
* @param request
* @param charset
*/
public GetHttpServletRequestWrapper(HttpServletRequest request,
String charset) {
super(request);
this.charset = charset;
}
/**
* 实际上就是调用被包装的请求对象的getParameter方法获得参数,然后再进行编码转换
*/
public String getParameter(String name) {
String value = super.getParameter(name);
value = value == null ? null : convert(value);
return value;
}
public String convert(String str) {
try {
return new String(str.trim().getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
return str;
}
}
}