【Java】全站编码过滤器GenericEncodingFilter代码与配置

编码过滤器GenericEncodingFilter:

 
  1 package com.fuck.web.filter;
  2 
  3 import java.io.IOException;
  4 import java.io.UnsupportedEncodingException;
  5 import java.util.Map;
  6 
  7 import javax.servlet.Filter;
  8 import javax.servlet.FilterChain;
  9 import javax.servlet.FilterConfig;
 10 import javax.servlet.ServletException;
 11 import javax.servlet.ServletRequest;
 12 import javax.servlet.ServletResponse;
 13 import javax.servlet.http.HttpServletRequest;
 14 import javax.servlet.http.HttpServletRequestWrapper;
 15 
 16 /**
 17  * 解决get和post请求 全部乱码
 18  * 
 19  * @author seawind
 20  * 
 21  */
 22 public class GenericEncodingFilter implements Filter {
 23 
 24     @Override
 25     public void destroy() {
 26     }
 27 
 28     @Override
 29     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
 30         // 转型为与协议相关对象
 31         HttpServletRequest httpServletRequest = (HttpServletRequest) request;
 32         // 对request包装增强
 33         HttpServletRequest myrequest = new MyRequest(httpServletRequest);
 34         response.setContentType("text/html;charset=utf-8");
 35         chain.doFilter(myrequest, response);
 36     }
 37 
 38     @Override
 39     public void init(FilterConfig filterConfig) throws ServletException {
 40     }
 41 
 42 }
 43 
 44 // 自定义request对象
 45 class MyRequest extends HttpServletRequestWrapper {
 46 
 47     private HttpServletRequest request;
 48 
 49     private boolean hasEncode;
 50 
 51     public MyRequest(HttpServletRequest request) {
 52         super(request);// super必须写
 53         this.request = request;
 54     }
 55 
 56     // 对需要增强方法 进行覆盖
 57     @Override
 58     public Map getParameterMap() {
 59         // 先获得请求方式
 60         String method = request.getMethod();
 61         if (method.equalsIgnoreCase("post")) {
 62             // post请求
 63             try {
 64                 // 处理post乱码
 65                 request.setCharacterEncoding("utf-8");
 66                 return request.getParameterMap();
 67             } catch (UnsupportedEncodingException e) {
 68                 e.printStackTrace();
 69             }
 70         } else if (method.equalsIgnoreCase("get")) {
 71             // get请求
 72             Map<String, String[]> parameterMap = request.getParameterMap();
 73             if (!hasEncode) { // 确保get手动编码逻辑只运行一次
 74                 for (String parameterName : parameterMap.keySet()) {
 75                     String[] values = parameterMap.get(parameterName);
 76                     if (values != null) {
 77                         for (int i = 0; i < values.length; i++) {
 78                             try {
 79                                 // 处理get乱码
 80                                 values[i] = new String(values[i].getBytes("ISO-8859-1"), "utf-8");
 81                             } catch (UnsupportedEncodingException e) {
 82                                 e.printStackTrace();
 83                             }
 84                         }
 85                     }
 86                 }
 87                 hasEncode = true;
 88             }
 89             return parameterMap;
 90         }
 91 
 92         return super.getParameterMap();
 93     }
 94 
 95     @Override
 96     public String getParameter(String name) {
 97         Map<String, String[]> parameterMap = getParameterMap();
 98         String[] values = parameterMap.get(name);
 99         if (values == null) {
100             return null;
101         }
102         return values[0]; // 取回参数的第一个值
103     }
104 
105     @Override
106     public String[] getParameterValues(String name) {
107         Map<String, String[]> parameterMap = getParameterMap();
108         String[] values = parameterMap.get(name);
109         return values;
110     }
111 
112 }

 

WEB-INF下的web.xml配置:

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>estoredemo</display-name>
  <filter>
     <filter-name>GenericEncodingFilter</filter-name>
     <filter-class>com.fuck.web.filter.GenericEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>GenericEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

=================================================================================================

网上看到另一个,其实和上面基本一模一样,不过也贴上做个备份吧

 1 import java.io.IOException;  
 2 import java.util.Map;  
 3   
 4 import javax.servlet.Filter;  
 5 import javax.servlet.FilterChain;  
 6 import javax.servlet.FilterConfig;  
 7 import javax.servlet.ServletException;  
 8 import javax.servlet.ServletRequest;  
 9 import javax.servlet.ServletResponse;  
10 import javax.servlet.http.HttpServletRequest;  
11 import javax.servlet.http.HttpServletRequestWrapper;  
12   
13 public class EncodingFilter implements Filter {  
14     private FilterConfig config = null;  
15     private String encode = null;  
16      
17      public void destroy() {  
18          
19     }  
20   
21     public void doFilter(ServletRequest request, ServletResponse response,  
22             FilterChain chain) throws IOException, ServletException {  
23         response.setContentType("text/html;charset="+encode); //--解决响应乱码  
24         //--包装改造request中和获取请求参数相关的方法解决请求参数乱码  
25         chain.doFilter(new MyHttpServletRequest((HttpServletRequest) request), response);  
26     }  
27      
28     public void init(FilterConfig filterConfig) throws ServletException {  
29         this.config = filterConfig;  
30         encode = config.getInitParameter("encode") == null?"utf-8":config.getInitParameter("encode");  
31     }  
32   
33   
34   
35     //内部类,装饰类改造HttpServletRequest   的三个方法  
36     class MyHttpServletRequest extends HttpServletRequestWrapper{  
37         private HttpServletRequest request = null;  
38         private boolean isNotEncode = true;  
39         public MyHttpServletRequest(HttpServletRequest request) {  
40             super(request);  
41             this.request = request;  
42         }  
43          
44         @Override  
45         public Map getParameterMap() {  
46             try{  
47                 if(request.getMethod().equalsIgnoreCase("POST")){//--如果是post提交,一行代码解决post提交请求参数乱码  
48                     request.setCharacterEncoding(encode);  
49                     return request.getParameterMap();  
50                 }else if(request.getMethod().equalsIgnoreCase("GET")){//--如果是get提交,则应该手动编解码解决乱码  
51                     Map<String,String[]> map = request.getParameterMap();//获取有乱码的map  
52                     if(isNotEncode){//只能在第一次解决乱码  
53                         for(Map.Entry<String, String[]> entry : map.entrySet()){//遍历map,解决所有值的乱码  
54                             String [] vs = entry.getValue();  
55                             for(int i=0;i<vs.length;i++){  
56                                 vs[i] = new String(vs[i].getBytes("iso8859-1"),encode);  
57                             }  
58                         }  
59                         isNotEncode = false;//设置为false,第二次就不会再进这个代码块了  
60                     }  
61                     return map;  
62                 }else{  
63                     return request.getParameterMap();  
64                 }  
65             }catch (Exception e) {  
66                 e.printStackTrace();  
67                 throw new RuntimeException(e);  
68             }  
69         }  
70          
71         @Override  
72         public String[] getParameterValues(String name) {  
73             return (String[]) getParameterMap().get(name);  
74         }  
75          
76         @Override  
77         public String getParameter(String name) {  
78             return getParameterValues(name) == null ? null : getParameterValues(name)[0];  
79         }  
80     }  
81 }  
<filter>  
    <description>全站乱码过滤器</description>  
    <filter-name>encodeFilter</filter-name>  
    <filter-class>com.java.filter.EncodingFilter</filter-class>  
    <init-param>  
        <param-name>encode</param-name>  
        <param-value>utf-8</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>encodeFilter</filter-name>  
    <url-pattern>/*</url-pattern> -----------------------------------------拦截的路径  
</filter-mapping>  

 

posted @ 2017-01-12 15:26  多弗朗明哥  阅读(1530)  评论(0编辑  收藏  举报