利用过滤器和动态代理过滤敏感词

需求

  • 当客户端中包含敏感词时,服务器端资源使用requst.getParameter获取参数值时,要先在过滤器中利用动态代理对象处理接收到的参数值后放行。
  • 例如:敏感词包括 笨蛋 蠢,服务器端有testServlet资源,当客户端输入http://localhost:8080/testServlet?msg=笨蛋吧 ,在服务器端中的过滤器中利用动态代理对象 将敏感次替换为***,然后进行后续处理

SensitiveWordFilter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@WebFilter("/*")
public class SensitiveWordFilter implements Filter {
public void destroy() {
}

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//创建动态代理对象,增强getParameter方法
ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//增强getParameter方法
//判断是否是getParameter方法
if (method.getName().equals("getParameter")){
//调用目标对象的getParameter,增强返回值
String res = (String) method.invoke(req, args);//将目标对象传递进去
if (res!=null){
//遍历敏感词列表
for (String str : list) {
if (res.contains(str)){
res = res.replaceAll(str, "***");
}
}
}
//返回增强后的值给request.getParameter(str)
return res;
}
return method.invoke(req, args);//当不执行getParameter方法时,仅执行method.invoke
}
});
//传递req的代理对象
chain.doFilter(proxy_req, resp);
}
//定义一个敏感词集合
private List<String> list = new ArrayList<String>();
public void init(FilterConfig config) throws ServletException {
try {
//获取文件的真实路径,加载文件
ServletContext servletContext = config.getServletContext();
String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感词.txt");
//读取文件
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(realPath), "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//将每一行的数据添加到集合中
String line = null;
while ((line = bufferedReader.readLine())!=null){
list.add(line);
}
bufferedReader.close();
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
}
}
}

testServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
@WebServlet("/testServlet")
public class testServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过Proxy_req对象调用getParameter方法,这里的request是Filter放行后的代理对象proxy_req
String msg = request.getParameter("msg");
System.out.println(msg);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}