Fitter-案例-过滤敏感词汇-分析
需求:
1. 对day17_case案例录入的数据进行敏感词汇过滤
2. 敏感词汇参考《敏感词汇.txt》
3. 如果是敏感词汇,替换为 **
分析:
1. 对request对象进行增强。增强获取参数相关方法
2. 放行。传递代理对象
Fitter-案例-过滤敏感词汇-代码实现
package com.example.day17_case.web.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.BufferedReader; 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 (Exception 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() { Filter.super.destroy(); } }
package com.example.day17_case.web.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("/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,Fitter,req,过滤,import,servlet From: https://www.cnblogs.com/yuzong/p/17077274.html