#04.Java Web中:使用Filter过滤器过滤评论中的非法字符并替换为*号

旨在: 判断用户发送的评论是否包含一些非法词汇,替换成*号, 屏蔽词库由配置文件提供.

1.解决中文乱码的filter

@WebFilter("/*")
public class CharEncodingFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //统一设置请求的编码方式为UTF-8
        req.setCharacterEncoding("UTF-8");
        //统一设置响应的编码方式(如果设置了这种解决响应乱码的代码,那么就不能做下载)
        resp.setContentType("text/html;charset=UTF-8");
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}

2.过滤非法字符的filter

(这里的 过滤词库.txt,每一行为一个关键词,当作配置文件放到properties文件夹下)

@WebFilter("/*")
public class IllegalCharFilter implements Filter {
    private List<String> strList = new ArrayList<>();
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //放行之前,使用动态代理技术,增强req对象的方法
        //将req强转成HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) req;
        //类加载器
        ClassLoader classLoader = req.getClass().getClassLoader();
        //被代理的接口: HttpServletRequest
        HttpServletRequest requestProxy = (HttpServletRequest) Proxy.newProxyInstance(classLoader, new Class[]{HttpServletRequest.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //增强getParameter()方法,其它方法还是调用被代理者原本的方法
                if (method.getName().equals("getParameter")) {
                    //要增强getParameter()方法,其实就是将请求参数值中的非法字符替换成*
                    //1. 获取请求参数值
                    String value = (String) method.invoke(request, args);
                    //2. 判断请求参数值中是否包含非法字符
                    for (String str : strList) {
                        if (value.contains(str)) {
                            //2.1 包含非法字符,就要将value中的非法字符替换成*
                            String start = "";
                            for (int i=0;i<str.length();i++){
                                start += "*";
                            }
                            value = value.replace(str,start);
                        }
                    }
                    return value;
                }
                //不用增强的方法,要调用被代理者原本的方法
                return method.invoke(request,args);
            }
        });

        //最后肯定要放行
        chain.doFilter(requestProxy, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        //读取IllegalWords.txt里面的数据
        //1. 将IllegalWords.txt转换成字节输入流
        InputStream is = IllegalCharFilter.class.getClassLoader().getResourceAsStream("IllegalWords.txt");
        //2. 将字节输入流,包装成BufferReader
        try {
            BufferedReader bfr = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String  str = null;
            while (( str = bfr.readLine()) != null) {
                //每读到一个字符串,就将它存储到strList中
                strList.add(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.servlet

@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String content = request.getParameter("content");
        response.getWriter().write("评论成功,评论内容为:"+content);
    }
}

4.其他部分省略

你可能感兴趣的:(Java日记)