デリケートな単語をフィルタリングする

個人ブログ
デリケートな単語フィルタリングするには、リクエストオブジェクトを拡張し、パラメータを取得するための関連メソッドを拡張してから、デリケートな単語を***に置き換える必要があります プロキシモードを使用する

フィルターの準備

@WebFilter("/*")
public class SensitiveFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //创建代理对象增强getparammeter方法
        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 {
                //是否是getParameter方法
                if (method.getName().equals("getParameter")){
                    //增强返回值
                    String value = (String) method.invoke(req,args);
                    if (value != null){
                        for (String str : list) {
                            if (value.contains(str)){
                                value = value.replaceAll(str,"***");
                            }
                        }
                    }
                    return value;
                }
                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");
            //读取文件
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            //将文件每一行数据添加到list中
            String line = null;
            while ((line = br.readLine())!= null){
                list.add(line);
            }
            br.close();
            System.out.println(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void destroy() {
    }

}

テストクラスの作成

@WebServlet("/testServlet")
public class TestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String msg = request.getParameter("msg");
        System.out.println(name+":"+msg);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

デリケートな語彙ファイル

フール
悪者を

元の記事を28件公開 賞賛された0 訪問数722

おすすめ

転載: blog.csdn.net/William_GJIN/article/details/105020131