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 55
| @WebFilter( filterName = "SensitiveWordsFilter", urlPatterns = "/*", initParams = { @WebInitParam(name="word1", value="笨蛋"), @WebInitParam(name="word2", value="傻蛋"), @WebInitParam(name="word3", value="蠢蛋") } ) public class SensitiveWordsFilter implements Filter { private List<String> sensitiveWords = new ArrayList<>(); @Override public void init(FilterConfig config) throws ServletException { Enumeration<String> parameterNames = config.getInitParameterNames(); while (parameterNames.hasMoreElements()) { String sensitiveWord = config.getInitParameter(parameterNames.nextElement()); sensitiveWords.add(sensitiveWord); } }
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletRequest requestProxy = (HttpServletRequest) Proxy.newProxyInstance( request.getClass().getClassLoader(), request.getClass().getInterfaces(), (proxy, method, args) -> { Object returnValue = null; String methodName = method.getName(); if ("getParameter".equals(methodName)) { String word = (String) method.invoke(request, args); for (String sensitiveWord : sensitiveWords) { if (word.contains(sensitiveWord)) { returnValue = word.replace(sensitiveWord, "***"); } } } else { returnValue = method.invoke(request, args); } return returnValue; } ); chain.doFilter(requestProxy, resp); }
@Override public void destroy() { } }
|