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 }