通过过滤器进行敏感词汇的屏蔽

我们需要通过过滤器进行拦截,将request中的getparameter()方法进行覆盖把包含敏感词的池中的敏感词进行遍历然后一次屏蔽

package cn.hncu.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import cn.hncu.pub.wordUtils;

public class wordFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        myrequest request2 = new myrequest((HttpServletRequest) request);
        chain.doFilter(request2, response);
    }

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

    }

    // 这个HttpServletRequestWrapper就是包装类,专门用来写包装类的
    class myrequest extends HttpServletRequestWrapper {
        public myrequest(HttpServletRequest request) {
            super(request);
        }

        // 在这里屏蔽敏感词,覆盖原先的getParameter方法
        @Override
        public String getParameter(String name) {
            String val = super.getParameter(name);
            System.out.println(val);
            List list = wordUtils.getwords();
            for (String s : list) {
                val = val.replaceAll(s, "***");
                System.out.println("屏蔽敏感词" + s);
            }
            return val;
        }
    }
}

你可能感兴趣的:(过滤器)