web.xml设置编码格式---在filter 过滤并设置当前要设置的编码格式

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
           HttpServletRequest req = (HttpServletRequest) request;
           HttpServletResponse res = (HttpServletResponse) response;

           /*
            *判断在web.xml中是否设置了编码格式的信息
            *如果为null 则设置为web.xml的编码格式
            *否则设置UTF-8
            */
           if(this.encode != null && !this.encode.equals("")) {
                request.setCharacterEncoding(this.encode);
                response.setCharacterEncoding(this.encode);
           }else {
                request.setCharacterEncoding("utf-8");
                response.setCharacterEncoding("utf-8");
           }
           chain.doFilter(request, response);
     }
     //初始化时获取encode的信息
     public void init(FilterConfig fConfig) throws ServletException {
           this.encode = fConfig.getInitParameter("encode");
     }
     


你可能感兴趣的:(代码片段大全)