一、乱码原因
①传输方和接收方采用的编码不一致。传输方对参数采用的是UTF-8编码而接收方却用GBK进行解析,当然是乱码。
②Tomcat服务器默认采用的ISO8859-1编码得到参数值。虽然①中采用了同样的编码方式,但经过tomcat一处理,也会出现乱码(GET方式)
二、解决办法
方法一 每次传输都手动设置编码(GET方式传输数据)
传输方
String name = URLEncoder.encode("徐越","UTF-8");
String path = "http://localhost:8008/xyWeb/xyServlet?name=" + name;
接收方
String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
若传输方默认采用UTF-8编码就没有必要每次写,但接收方每次都写太烦,可考虑过滤器。
方法二(过滤器)
/**
* 编码过滤器
*
* @author 徐越
*
*/
public class EncodingFilter implements Filter
{
private String encoding;
public void init(FilterConfig fConfig) throws ServletException
{
encoding = fConfig.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception
{
HttpServletRequest httprequest = (HttpServletRequest) request;
if ("GET".equals(httprequest.getMethod()))
{
// 将httpRequest进行包装
EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(httprequest, encoding);
chain.doFilter(wrapper, response);
}
else
{
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset=" + encoding);
chain.doFilter(request, response);
}
}
public void destroy()
{
}
}
/**
* httpRequest进行包装类
*
* @author 徐越
*
*/
public class EncodingHttpServletRequest extends HttpServletRequestWrapper
{
private HttpServletRequest request;
private String encoding;
public EncodingHttpServletRequest(HttpServletRequest request)
{
super(request);
this.request = request;
}
public EncodingHttpServletRequest(HttpServletRequest request,String encoding)
{
super(request);
this.request = request;
this.encoding = encoding;
}
@Override
public String getParameter(String name)
{
String value = request.getParameter(name);
if (null != value)
{
try
{
// tomcat默认以ISO8859-1处理GET传来的参数。把tomcat上的值用ISO8859-1获取字节流,再转换成UTF-8字符串
value = new String(value.getBytes("ISO8859-1"), encoding);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
return value;
}
}
<filter>
<display-name>EncodingFilter</display-name>
<filter-name>EncodingFilter</filter-name>
<filter-class>cn.xy.filter.EncodingFilter</filter-class>
<init-param>
<description></description>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>