JavaWeb中的filter过滤敏感词汇案例
需求:对含有bad.txt中的敏感词汇的句子进行替换,替换成星号
bad.txt放在src目录下
笨蛋
坏蛋
FilterDemo
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 FilterDemo8 implements Filter {
//读取txt文件时将词汇存入列表
private List<String> list = new ArrayList<String>();
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//通过代理增强方法
ServletRequest proxy = (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 obj = (String) method.invoke(req, args);
if (obj != null){
//遍历后替换词汇
for (String s : list) {
if (obj.contains(s)){
obj = obj.replaceAll(s,"***");
}
}
}
return obj;
}
return method.invoke(req,args);
}
});
//放行
chain.doFilter(proxy,resp);
}
public void init(FilterConfig config) throws ServletException {
//读取文件
ServletContext context = config.getServletContext();
//src下的文件真实位置是在WEN-INF/classes下的
String realPath = context.getRealPath("/WEB-INF/classes/bad.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(realPath));
String line = null;
while ((line = reader.readLine()) != null){
list.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
servlet
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/servletDemo")
public class ServletDemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String what = request.getParameter("what");
System.out.println(name + " : " + what);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}