demand:
1, the data entry day17_case cases be sensitive words filter
2, "sensitive words .txt" under src sensitive lexical reference path
3, if it is sensitive words, replaced ***
analysis:
1, subject to request enhanced. Enhancing acquisition parameters associated method
2, release. Delivery Agent objects
Code:
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 publicInvoke Object (Object O, Method, Method, Object [] args) throws the Throwable {
25
26 is // enhancement method getparameter
27 // determining whether the method is
28 IF (method.getName (). The equals ( "the getParameter" )) {
29 // enhanced return value
30 // returns a value
31 is String value = (String) Method.invoke (REQ, args);
32
33 is IF (value =! null ) {
34 is for (STR String: List) {
35 IF (value .Contains (STR)) {
36 = value.replaceAll value (STR, "***" );
37 [ }
38 is }
39 }
40
41 is return value;
42 is }
43 is
44 is return Method.invoke (REQ, args);
45 }
46 is });
47 // 2 release, delivery enhancing proxy objects
48
49 the chain.doFilter (proxy_req, RESP);
50 }
51 is
52 is
53 is Private List <String> List = new newThe ArrayList <String> (); // sensitive word set
54 is public void the init (the FilterConfig config) throws ServletException {
55
56 is
57 is the try {
58 // . 1 load file
59 // Get File real path
60 the ServletContext where servletContext = config.getServletContext ( );
61 is String realpath = ServletContext.getRealPath ( "/ the WEB-INF / classes / sensitive words .txt" );
62 is // 2 read the file
63 is
64 the BufferedReader br = new new the BufferedReader ( new newThe FileReader (realpath));
65
66 // each line of the file 3 is added to the list
67
68 String Line = null ;
69 the while ! ((Line = br.readLine ()) = null ) {
70 List.add (Line );
71 is }
72
73 is br.close ();
74
75 System.out.println (List);
76 } the catch (Exception E) {
77 e.printStackTrace ();
78 }
79
80 }
81
82
83 public void destroy() {
84 }
85
86 }