Filter过滤敏感词汇案例
Filter过滤敏感词汇案例
需求∶
1.对用户信息案例录入的数据进行敏感词汇过滤
2.敏感词汇参考 傻蛋.坏蛋......
3.如果是敏感词汇,替换为***
分析:
1.对request对象进行增强。增强获取参数相关方法
2.放行。传递代理对象
SensitiveWordsFilter:
/** * 敏感词汇过滤器 */ @WebFilter("/*") public class SensitiveWordsFilter 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方法 if (method.getName().equals("getParameter")){ //增强返回值 //获取返回值 String value = (String) method.invoke(req, args); if (value!=null){ for (String str : list) { if (value.contains(str)){ value = value.replaceAll(str,"***"); } } } return value; } //判断是否是getParameterMap if (method.getName().equals("getParameterMap")){ Map<String,String[]>map=(Map<String, String[]>) method.invoke(req,args);//真实返回值 Map<String,String[]> remap=new HashMap<>(); Set<String> strings = map.keySet(); for (String key:strings){//遍历map String value[]=map.get(key); for (String str:list){//遍历敏感词 if (value[0].contains(str)){ value[0]=value[0].replaceAll(str,"***"); } } } return map; } //判断是否是getParameterValue if (method.getName().equals("getParameterValue")){ String values[]= (String[]) method.invoke(req,args); for (int i=0;i<values.length;i++){ for (String str:list){ if (values[i].equals(str)){ values[i]=values[i].replaceAll(str,"***"); } } } return values; } return method.invoke(req,args); } }); chain.doFilter(proxy_req, resp); } public 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"); //读取文件 BufferedReader br = new BufferedReader(new FileReader(realPath)); String len = null; while ((len=br.readLine())!=null){ list.add(len); } br.close(); System.out.println(list); }catch (IOException e) { e.printStackTrace(); } } }
敏感词汇.txt:GBK形式
乱码的需要用这个new BufferedReader(new InputStreamReader(new FileInputStream(realPath),"GBK"))
TestServlet测试:访问
@WebServlet("/testServlet") public class TestServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String msg = request.getParameter("msg"); System.out.println(name+":"+msg); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
控制台替换成功: