解决Tomcat7中文乱码问题

最近使用ssh框架写一个小项目时,发现使用tomcat7,post和get请求会出现中文乱码的为问题,spring框架下提供了一个CharacterEncodingFilter类来解决post中文乱码的问题

在web.xml里配置过滤器


  	characterEncodingFilter
  	org.springframework.web.filter.CharacterEncodingFilter
  	
  		encoding
  		UTF-8
  	
  
  
  	characterEncodingFilter
  	/*
  


由于CharacterEncodingFilter类中只提供了对post请求中文乱码的解决方案,所以可以自定义一个类来解决post和get两种请求的中文乱码问题

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;


/**
 * 解决tomcat7 post和get请求中文乱码问题
 */
public class MyEncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //1.设置POST请求中文乱码的问题
        request.setCharacterEncoding("utf-8");

        //2.解决GET请求中文乱码的问题
        HttpServletRequest hsr = (HttpServletRequest) request;
        if(hsr.getMethod().equalsIgnoreCase("get")){
            MyRequest myRequest = new MyRequest(hsr);

            //放行请求
            filterChain.doFilter(myRequest,response);
        }else{
            filterChain.doFilter(request,response);
        }

    }

    @Override
    public void destroy() {
    }

    /**
     * 自定义包装类
     */
    private class MyRequest extends HttpServletRequestWrapper {
        private HttpServletRequest request;
        private boolean isEncoding = false; //是否已经utf-8编码

        public MyRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        @Override
        public String getParameter(String name) {
            return getParameterMap().get(name)[0];
        }

        @Override
        public Map getParameterMap() {
            Map map = request.getParameterMap();

            if(isEncoding == true){
                return map;
            }

            //遍历value, 改成utf-8编码
            for(Entry entry : map.entrySet())
            {
                //取数组值
                String[] values = entry.getValue();

                for (int i = 0; i < values.length; i++) {
                    try {
                        values[i] = new String(values[i].getBytes("ISO-8859-1"),"utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            isEncoding = true;
            return map;
        }
    }
}

web.xml配置


    
        encodingFilter
        com.gyf.bos.web.filter.MyEncodingFilter
    
    
        encodingFilter
        /*
    

你可能感兴趣的:(Java)