018.代理模式结和Filter做的一个屏蔽敏感词汇
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>过滤器应用示例---敏感词过滤</title> </head> <body> <form action="noteServlet" method="post" accept-charset="UTF-8" > 姓名:<input type="text" name="name"> <br> 留言:<input type="text" name="note" ><br> <input type="submit" value="提交"> </form> </body> </html>
package com.item.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; /** * 1.分析: * 1.1 对request对象进行增强。增强获取参数相关方法 * 1.2 放行。传递代理对象 * 2.实现敏感词汇的过滤 */ @WebFilter("/*") public class SenstiveWordsFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { /** * 1.创建代理对象,增强getParameter方法 * 2.放行 */ ServletRequest proxyServletRequest = (ServletRequest) Proxy.newProxyInstance(servletRequest.getClass().getClassLoader(), servletRequest.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /** * 1.增强getParameter方法 * 2.首先要判断是不是getParameter方法 */ if (method.getName().equals("getParameter")) { /** * 1.增强返回值 * 2.获取返回值进行铭感词汇的过滤 */ String value = (String) method.invoke(servletRequest, args); if (value != null) { for (String str : list) { if (value.contains(str)) { value = value.replaceAll(str, "**"); } } } return value; } /** * 1.如果不是就执行正是对象的方法 */ return method.invoke(servletRequest, args); } }); filterChain.doFilter(proxyServletRequest, servletResponse); } private List<String> list = new ArrayList<String>();//存放敏感词汇的集合 @Override public void init(FilterConfig filterConfig) throws ServletException { /** * 1.将数据词汇添加到list中 * 2.对于Filter中的init()初始化方法仅执行一次,即初始化一次 */ list.add("蠢货"); list.add("傻逼"); list.add("蠢蛋"); } }
package com.item.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("/noteServlet") public class NoteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /** * 1.解决乱码 */ req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); String name=req.getParameter("name"); String note = req.getParameter("note"); resp.getWriter().write(name+"的留言是:"+note); System.out.println(name+":"+note); } }