servlet过滤器的使用

过滤器,在请求servlet之前,先用调用过滤器

1.过滤器在web.xml中的配置

 
    filter1
    web.CommentFilter1


    filter1
    /process

2.过滤器类首先要implements Filter

然后重写doFilter()方法在这个方法中写过滤代码

    public void doFilter(ServletRequest arg0,
            ServletResponse arg1, FilterChain arg2)
    throws IOException, ServletException {
        System.out.println("Filter1 begin filter...");
        HttpServletRequest request =
            (HttpServletRequest)arg0;
        HttpServletResponse response =
            (HttpServletResponse)arg1;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String comment = request.getParameter("comment");
        String illegalStr =
            config.getInitParameter("illegalStr");
        if(comment.indexOf(illegalStr) > 0){
            out.println("illegal comment.");
        }else{
            //调用后续的过滤器,如果没有了,则调用web组件
            arg2.doFilter(arg0, arg1);
        }
        System.out.println("Filter1 process finished.");
    }


 /**
     * servlet容器在创建好Filter实例之后,会立即调用
     * init()方法。容器会创建FilterConfig实例,通过该
     * 实例,可以访问Filter的初始化参数。
     * String FilterConfig.getInitParameter(String paraName);
     * init()方法只会执行一次。
     */

 

3.web.xml配置参数的过滤器

web.xml中的配置

     filter1

    web.CommentFilter1

   

        illegalStr

        cat

   

 

    filter1

    /process

过滤器类

public class CommentFilter2 implements Filter{
    private FilterConfig config;
    public void destroy() {
    }
    public void doFilter(ServletRequest arg0,
            ServletResponse arg1, FilterChain arg2)
        throws IOException, ServletException {
        System.out.println("Filter2 begin process...");
        HttpServletRequest request =
            (HttpServletRequest)arg0;
        HttpServletResponse response =
            (HttpServletResponse)arg1;
        String comment = request.getParameter("comment");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        int size = Integer.parseInt(
                config.getInitParameter("size"));
        if(comment.length() > size){
            out.println("illegal size.");
        }else{
            arg2.doFilter(arg0, arg1);
        }
        System.out.println("Filter2 process finished.");
    }
    public void init(FilterConfig arg0) throws ServletException {
        config = arg0;
    }
}

 

 

你可能感兴趣的:(servlet)