1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| @WebFilter("/*") public class SensitiveWordFilter 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 res = (String) method.invoke(req, args); if (res!=null){ for (String str : list) { if (res.contains(str)){ res = res.replaceAll(str, "***"); } } } return res; } return method.invoke(req, args); } }); chain.doFilter(proxy_req, resp); } private 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"); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(realPath), "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line = null; while ((line = bufferedReader.readLine())!=null){ list.add(line); } bufferedReader.close(); System.out.println(list); } catch (Exception e) { e.printStackTrace(); } } }
|