[Java] 纯文本查看 复制代码
@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {
private List<String> list = new ArrayList<>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//1.获取文件的真实路径
ServletContext context = filterConfig.getServletContext();
String realPath = context.getRealPath("/WEB-INF/classes/敏感词汇.txt");
//2.读取realPath中的敏感词汇
try (FileInputStream fis = new FileInputStream(realPath);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));) {
//3.使用br读取敏感词汇
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
System.out.println(list);
//4.不用释放资源了,fis和br的作用域仅在这个try中
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
//0.强制转型
HttpServletRequest request = (HttpServletRequest) req;
//1.创建proxy_req对象
HttpServletRequest proxy_req = (HttpServletRequest) Proxy.newProxyInstance(request.getClass().getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
//2.1 判断方法是否为getParameter对象
if (methodName.equals("getParameter")) {
String value = (String) method.invoke(request, args);
if (value != null) {
for (String str : list) {
value = value.replaceAll(str, "***");
}
}
return value;
}
//2.2判断方法是否为getParameterValues
if (methodName.equals("getParameterValues")) {
String[] values = (String[]) method.invoke(request, args);
List<String> sb = new ArrayList<>();
if (values != null) {
for (String value : values) {
for (String str : list) {
value = value.replaceAll(str, "***");
}
sb.add(value);
}
}
String[] sBuffer = new String[values.length];
String[] sb_string = sb.toArray(sBuffer);
return sb_string;
}
//2.3判断方法是否为getParameterMap
if (methodName.equals("getParameterMap")) {
Map<String, String[]> map = (Map<String, String[]>) method.invoke(request, args);
Set<String> keys = map.keySet();
Map<String, Object> newMap = new HashMap<>();
for (String key : keys) {
String[] values = map.get(key);
List<String> sb = new ArrayList<>();
for (String value : values) {
for (String str : list) {
value = value.replaceAll(str, "***");
}
sb.add(value);
}
String[] sBuffer = new String[values.length];
String[] sb_string = sb.toArray(sBuffer);
newMap.put(key, sb_string);
}
return newMap;
}
return method.invoke(request, args);
}
});
//3.放行
chain.doFilter(proxy_req, resp);
}
@Override
public void destroy() {
}
}