首页 > 代码库 > java web中get请求中文乱码在filter中解决

java web中get请求中文乱码在filter中解决

之前已经讲过get或者post方法的中文乱码问题,之前都是在每个方法中编写设置编码。如果程序变大,就会很繁琐,使用filter可以避免这种繁琐。

1)写一个encodingFilter进行编码设置

public class encodingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res; 
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        arg2.doFilter(new encodingRequestServlet(request), response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }
    
    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }
}

 

2)在该方法中使用了一个继承自 HttpServletRequestWrapper 的类,该类可以覆盖HttpServletRequest 类中的方法

我们只需要重写 getParameter 方法即可。

public class encodingRequestServlet extends HttpServletRequestWrapper {
    private HttpServletRequest request;

    public encodingRequestServlet(HttpServletRequest request) {
        super(request);
        this.request = request;
    }
    
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if(value =http://www.mamicode.com/= null)
            return value;
        String method = request.getMethod();
        if("get".equalsIgnoreCase(method)){
            try {                
                value = new String(value.getBytes("ISO8859-1"),"utf-8");                
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        
        return value;
    }
}

 

java web中get请求中文乱码在filter中解决