需求:
1、 對day17_case案例錄入的數據進行敏感詞匯過濾
2、 敏感詞匯參考 src路徑下的《敏感詞匯.txt》
3、 如果是敏感詞匯,替換為 ***
分析:
1、 對request對象進行增強。增強獲取參數相關方法
2、 放行。傳遞代理對象
代碼實現:
1 import org.springframework.cglib.proxy.InvocationHandler; 2 import org.springframework.cglib.proxy.Proxy; 3
4 import javax.servlet.*; 5 import javax.servlet.annotation.WebFilter; 6 import java.io.BufferedReader; 7 import java.io.FileReader; 8 import java.io.IOException; 9 import java.lang.reflect.Method; 10 import java.util.ArrayList; 11 import java.util.List; 12
13 /**
14 * 敏感詞匯過濾器 15 */
16 @WebFilter("/*") 17 public class SensitiveWordsFilter implements Filter { 18
19
20 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { 21 // 1 創建代理對象,增強 getparameter 方法
22 ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() { 23 @Override 24 public Object invoke(Object o, Method method, Object[] args) throws Throwable { 25
26 // 增強 getparameter 方法 27 // 判斷是否是該方法
28 if(method.getName().equals("getParameter")) { 29 // 增強返回值 30 // 獲取返回值
31 String value = (String) method.invoke(req,args); 32
33 if(value != null) { 34 for (String str : list) { 35 if(value.contains(str)){ 36 value = value.replaceAll(str,"***"); 37 } 38 } 39 } 40
41 return value; 42 } 43
44 return method.invoke(req,args); 45 } 46 }); 47 // 2 放行,傳遞增強的代理對象
48
49 chain.doFilter(proxy_req, resp); 50 } 51
52
53 private List<String> list = new ArrayList<String>(); // 敏感詞匯集合
54 public void init(FilterConfig config) throws ServletException { 55
56
57 try { 58 // 1 加載文件 59 // 獲取文件的真實路徑
60 ServletContext servletContext = config.getServletContext(); 61 String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感詞匯.txt"); 62 // 2 讀取文件
63
64 BufferedReader br = new BufferedReader(new FileReader(realPath)); 65
66 // 3 將文件的每一行添加到 list 中
67
68 String line = null; 69 while((line = br.readLine()) != null) { 70 list.add(line); 71 } 72
73 br.close(); 74
75 System.out.println(list); 76 } catch (Exception e) { 77 e.printStackTrace(); 78 } 79
80 } 81
82
83 public void destroy() { 84 } 85
86 }