Filter-案例-过滤敏感词汇-分析
需求:
1.对day17_case案例录入的数据进行敏感词汇过滤
2.敏感词汇参考《敏感词汇.txt》
3.如果是敏感词汇,替换为 * *
分析:
1.对request对象进行增强。增强获取参数相关方法
2.放行。传递代理对象
Filter-案例-过滤敏感词汇-代码实现
敏感词汇.txt
SensitiWordsFilter类
package com.jstl.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 SensitiveWordsFilter implements Filter { // 敏感词汇集合 private List<String> list = new ArrayList<String>(); @Override public void init(FilterConfig filterConfig) throws ServletException { try { // 获取文件真实路径 ServletContext servletContext = filterConfig.getServletContext(); String realPath = servletContext.getRealPath("/WEB-INF/敏感词汇.txt"); // 读取文件 BufferedReader bufferedReader = new BufferedReader(new FileReader(realPath)); // 将文件的每一行数据添加到list中 String line = null; while ((line = bufferedReader.readLine()) != null) { list.add(line); } bufferedReader.close(); System.out.println(list); } catch (IOException e) { e.printStackTrace(); } } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // 创建代理对象,增强getParameter方法 ServletRequest proxy_req = (ServletRequest)Proxy.newProxyInstance( servletRequest.getClass().getClassLoader(), servletRequest.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 增强getParameter方法 // 判断是否是getParameter方法 if (method.getName().equals("getParameter")) { // 增强返回值 // 获取返回值 String value = (String) method.invoke(servletRequest,servletResponse); if (value != null) { for (String str : list) { if (value.contains(str)) { value = value.replaceAll(str,"***"); } } } return value; } return method.invoke(servletRequest,args); } }); // 放行 filterChain.doFilter(proxy_req,servletResponse); } @Override public void destroy() { } }
TextServlet类
package com.jstl.web.servlet; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet("/textServlet") public class TextServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); String msg = req.getParameter("msg"); System.out.println(name+":"+msg); } }标签:敏感,词汇,java,String,req,Filter,过滤,import From: https://www.cnblogs.com/wsfj/p/17117938.html