欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javaweb中的过滤器Filter筛选非法字符

程序员文章站 2024-02-08 17:34:52
...

筛选非法字符

需求:

当用户发出非法言论的时候,提示用户言论非法。

步骤分析:

  1. 确定访问的是哪些连接
    • /day09_filter/words?kw=你是个笨蛋 //非法
    • /day09_filter/words?kw=你是个坏蛋 //非法
    • /day09_filter/words?kw=你是个Y蛋 //合法
  2. 编写一个properties文件,存放这些敏感词汇,规定通过","分割每个词汇
  3. 编写filter
    • 在filter的init方法中,加载properites配置文件,将敏感词放到集合中.
    • 在filter的doFilter方法中,获取用户提交过来的wd,判断参数中是否包含任意一个敏感词;若包含了提示用户且终止方法;若不包含,在控制上输出wd
  4. 编写WordsServlet,输出合法的kw。

代码实现:

@WebFilter("/ServletWords")
public class WordsFilter implements Filter {
    private List<String> wordList;

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

        try {
            //1.加载words.properties
            InputStream is = WordsFilter.class.getClassLoader().getResourceAsStream("words.properties");
            InputStreamReader isr = new InputStreamReader(is, "GBK");

            //2.将配置文件中的内容获取到(注意编码) : 坏蛋,笨蛋
            Properties prop = new Properties();
            prop.load(isr);

            String keyword = prop.getProperty("keyword");

            //3.将内容切割,转成数组,然后将数组变成list
            wordList = Arrays.asList(keyword.split(","));
            //System.out.println(wordList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //0.向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求参数 kw
        String param = request.getParameter("kw");

        //2.判断kw中有无非法字符 若有:提示用户,后面的代码不执行
        for (String word : wordList) {
            if (param.contains(word)) {
                response.getWriter().print("存在非法字符");
                return;
            }
        }

        //3.放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
@WebServlet("/ServletWords")
public class ServletWords extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("kw"));
        response.getWriter().print(request.getParameter("kw"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
相关标签: java filter