package cn.td.we.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {
//敏感词集合
private List<String> list = new ArrayList();
public void init(FilterConfig config) throws ServletException {
//获取文件路径
String path = config.getServletContext().getRealPath("/WEB-INF/classes/敏感词汇.txt");
//读取文件
try {
//读取UTF8文件
InputStreamReader isr = new InputStreamReader(new FileInputStream(path), "UTF-8");
BufferedReader br = new BufferedReader(isr);
/**
* 读取GBK编码文件BufferedReader流的编码默认为本地编码,如果本地编码为GBK,文件是UTF8,要用转换流转换
* BufferedReader br = new BufferedReader(new FileReader(path));
*/
//将文件数据封装到list中
String line = null;
while ((line = br.readLine())!=null){
list.add(line);
}
br.close();
isr.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
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方法
if(method.getName().equals("getParameter")){
//过滤
//获取返回值
String invoke = (String) method.invoke(req, args);
if(invoke!=null){
//替换敏感字符
for (String sensitiveWords : list) {
if(invoke.contains(sensitiveWords)){
invoke = invoke.replaceAll(sensitiveWords,"***");
}
}
}
return invoke;
}
return method.invoke(req,args);
}
});
//放行
chain.doFilter(proxy_req, resp);
}
public void destroy() {
}
}
敏感词过滤
最新推荐文章于 2024-07-11 14:20:05 发布