package com.ddup.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
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 SensitiveFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
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 {
if(method.getName().equals("getParameter")){
String test = (String) method.invoke(req, args);
if(test!=null) {
for (String s : list) {
System.out.println(s);
if (test.contains(s)) {
test = test.replaceAll(s, "***");
}
}
return test;
}
}
return method.invoke(req,args);
}
});
// String test = proxy_req.getParameter("test");
chain.doFilter(proxy_req, resp);
}
List<String> list=new ArrayList<String>();
public void init(FilterConfig config) throws ServletException {
//获得文件真实路径
ServletContext context = config.getServletContext();
String path = context.getRealPath("WEB-INF/classes/敏感词.txt");
//加载文件
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line=br.readLine())!=null){
list.add(line);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
|