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 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
14 //增強getParameter方法
15 //判斷是否是getParameter方法
16 if(method.getName().equals("getParameter")){
17 //增強傳回值
18 //擷取傳回值
19 String value = (String) method.invoke(req,args);
20 if(value != null){
21 for (String str : list) {
22 if(value.contains(str)){
23 value = value.replaceAll(str,"***");
24 }
25 }
26 }
27
28 return value;
29 }
30
31 //判斷方法名是否是 getParameterMap
32
33 //判斷方法名是否是 getParameterValues
34
35 return method.invoke(req,args);
36 }
37 });
38
39 //2.放行
40 chain.doFilter(proxy_req, resp);
41 }
42 private List<String> list = new ArrayList<String>();//敏感詞彙集合
43 public void init(FilterConfig config) throws ServletException {
44
45 try{
46 //1.擷取檔案真實路徑
47 ServletContext servletContext = config.getServletContext();
48 String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感詞彙.txt"); // 敏感詞彙.txt在src目錄下
49 //2.讀取檔案
50 BufferedReader br = new BufferedReader(new FileReader(realPath));
51 //3.将檔案的每一行資料添加到list中
52 String line = null;
53 while((line = br.readLine())!=null){
54 list.add(line);
55 }
56
57 br.close();
58
59 System.out.println(list);
60
61 }catch (Exception e){
62 e.printStackTrace();
63 }
64
65 }
66
67 public void destroy() {
68 }
69
70 }