中文乱码原因以及解决方案

1.产生原因

  在项目中从JSP页面传回来的中文在后台接受时变为乱码,因为JSP默认参数在传输过程中使用的编码为ISO-8859-1,而页面常用的是UTF-8编码,所以导致中文传回来是乱码,而英文没问题,ISO-8859-1就是英文编码。

  UTF-8是国际网络通用编码,是Unicode编码的网络实现版,当然兼容中英文。

  关于计算机编码,我可以推荐一个知乎上文章,链接如下:https://www.zhihu.com/question/23374078/answer/69732605

2.最佳解决方法

  2.1.在后台编写filter,将请求的参数都转换为UTF-8,代码如下:

  

package com.zy.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingFilter implements Filter{

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        //doFilter方法的第一个参数req,是ServletRequest 类型的,不支持setCharacterEncoding,
        //所以要先强制转换为HttpServletRequest 
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        req.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        
    }

}

  2.2.修改web.xml配置,添加编码filter,代码如下:

  

<!-- 中文过滤 -->
    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>com.zy.filter.EncodingFilter</filter-class>
    </filter>
     
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

posted @ 2018-01-26 12:40  anionic  阅读(2551)  评论(0编辑  收藏  举报