1 /** 2 * 敏感词汇过滤器 3 */ 4 @WebFilter("/*") 5 public class SensitiveWordsFilter implements Filter { 6 7 8 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { 9 //1.创建代理对象,增强getParameter方法 10 11 ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() { 12 @Override 13 is public Object Invoke (Object Proxy, Method, Method, Object [] args) throws the Throwable { 14 // enhancement method getParameter 15 // determines whether getParameter method 16 IF (method.getName (). The equals ( " getParameter " ) ) { 17 // reinforcing return value 18 // to obtain return . 19 String value = (String) Method.invoke (REQ, args); 20 is IF (value =! null ) { 21 is for (STR String: List) { 22 is IF (value.contains (str)) { 23 is value = value.replaceAll (STR, " *** " ); 24 } 25 } 26 is } 27 28 return value; 29 } 30 31 is // determines whether the method name getParameterMap 32 33 is // whether the judging method name is the getParameterValues 34 is 35 return Method.invoke (REQ, args); 36 } 37 [ }); 38 is 39 // 2. release 40 the chain.doFilter (proxy_req, RESP); 41 is } 42 is Private List <String> List = new new the ArrayList <String> (); // sensitive word set 43 is public void the init (the FilterConfig config) throws {ServletException 44 is 45 the try { 46 is // 1. obtain the true path file 47 the ServletContext where servletContext = config.getServletContext (); 48 String realpath = ServletContext.getRealPath ( " / the WEB-INF / classes / sensitive words .txt " ); // src sensitive words in .txt directory 49 // 2. read the file 50 Br = the BufferedReader new new the BufferedReader ( new new the FileReader (realpath)); 51 is // added to each row of the data file to 3. in list 52 is String Line = null ; 53 is the while (! (= Br.readLine Line ()) = null ) { 54 is List.add (Line); 55 } 56 is 57 is br.close (); 58 59 . the System OUT .println (List); 60 61 is } the catch (Exception E) { 62 is e.printStackTrace (); 63 is } 64 65 } 66 67 public void destroy() { 68 } 69 70 }