首页 > 代码库 > 过滤器实现编码过滤处理

过滤器实现编码过滤处理

 1 /**
 2  * 过滤器实现编码过滤
 3  * @author 王东海
 4  * @2017年4月17日
 5  */
 6 //定义拦截的资源,这里拦截的/*的所有
 7 @WebFilter(filterName="EncodeFilter",urlPatterns="/*")
 8 public class EncodeFilter implements Filter {
 9 
10     @Override
11     public void destroy() {
12 
13     }
14 
15     @Override
16     public void doFilter(ServletRequest arg0, ServletResponse arg1,
17             FilterChain chain) throws IOException, ServletException {
18         //在doFilter里面实现相应的拦截过滤 
19         /**
20          * 1、拦截目标,所有资源
21          * 2、get    post做相应的编码处理
22          * 3、放行我们的资源
23          */
24         
25         //1、先转换
26         HttpServletRequest request = (HttpServletRequest) arg0;
27         HttpServletResponse response = (HttpServletResponse) arg1;
28         //2、拿到它的请求类型
29         String method = request.getMethod();
30         response.setCharacterEncoding("utf-8");
31         
32         /**
33          * 做相应的判断
34          * 如果说拿到是get请求,需要对我们的request 进行包装,
35          * 包装需要继承一个HttpServletRequestWrapper类
36          */
37         if ("GET".equals(method)) {
38             
39             EncodeRequest encodeRequest = new EncodeRequest(request);
40             chain.doFilter(encodeRequest, response);
41         }else {
42             request.setCharacterEncoding("utf-8");
43             chain.doFilter(request, response);
44         }
45         
46     }
47 
48     @Override
49     public void init(FilterConfig arg0) throws ServletException {
50 
51     }
52 
53 }
 1 public class EncodeRequest extends HttpServletRequestWrapper {
 2 
 3     private HttpServletRequest request;
 4     
 5     public EncodeRequest(HttpServletRequest request) {
 6         super(request);
 7         //构造器里进行参数的接受
 8         this.request = request;
 9     }
10 
11     //需要重写getParameter方法
12     @Override
13     public String getParameter(String name) {
14 
15         String param = request.getParameter(name);
16         /**
17          * ISO8859-1 转换为 utf-8
18          */
19         //不为空的时候对它进行一个转换
20         if (!MyStringUtil.isNullOrEmpty(param)) {
21             
22             try {
23                 //先变为字节数据传入编码ISO8859-1转变为:utf-8
24                 param = new String(param.getBytes("ISO8859-1"),"utf-8");
25             } catch (UnsupportedEncodingException e) {
26                 e.printStackTrace();
27             }
28         }
29         
30         return param;
31     }
32 
33 }

 

过滤器实现编码过滤处理