806
技术社区[云栖]
JavaWeb项目的中文乱码的原因以及Servlet中处理GET请求和POST请求编码过滤器
一、乱码原因
①传输方和接收方采用的编码不一致。传输方对参数采用的是UTF-8编码而接收方却用GBK进行解析,当然是乱码。
②Tomcat服务器默认采用的ISO8859-1编码得到参数值。虽然①中采用了同样的编码方式,但经过tomcat一处理,也会出现乱码(GET方式)
二、解决办法
方法一 每次传输都手动设置编码(GET方式传输数据)
传输方
String name = URLEncoder.encode("张三","UTF-8");
String path = "https://localhost:8008/xyWeb/xyServlet?name=" + name;
接收方
String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
若传输方默认采用UTF-8编码就没有必要每次写,但接收方每次都写太烦,可考虑过滤器。
方法二(过滤器)
/** * 编码过滤器 * * @author xy * */ 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 xy * */ 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>
最后更新:2017-04-03 20:19:30
上一篇:
Oracle性能优化学习笔记之选择最有效率的表名顺序
下一篇:
C# 关于类型转换 面试题
私人定制——使用深度学习Keras和TensorFlow打造一款音乐推荐系统
hdu 1556 Color the ball 树状数组
MaxCompute模板与样例
cf 153.div2 D. Playing with Permutations
Dev BarManager控件要通过Remove成员来释放内存
Phalcon入门教程之模型CURD(1)
Java SSM 商户管理系统 客户管理 库存管理 进销存 项目源码 springmvc
hibernate之映射关系多对多
How the cloud is enabling a mobile workforce
Java 运算符