使用filter导致服务器返回的页面始终是空白---在doFilter中漏写了chain.doFilter()

今天调代码的时候,突然发现,服务器开着,什么都没有问题,当我把下面这个filter给deploy了以后,访问所有的页面就都是空白。

后来发现,是因为在代码路径中,有一条路径没有调用filterChain.doFilter(request, response),想来也是,你这不就等于把HttpServletRequest给丢失了么。

web.xml中,在enable=”false”的情况下,会出现我上面描述的问题,代码如下

package org.foo.filterdemo ;

import java.io.* ;

import javax.servlet.* ;

public class SimpleFilter implements Filter {

    private boolean enable = false;

    public void init(FilterConfig config)
          throws ServletException{
        String enableString = config.getInitParameter("enable");
        if (enableString != null && enableString.equalsIgnoreCase("true")) {
            this.enable = true;
        }
        String initParam = config.getInitParameter("ref") ;
        try {
            initParam = new String(initParam.getBytes("iso-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(this + ": init(), init-param = " + initParam);
    }
    public void doFilter(ServletRequest request,
              ServletResponse response,
              FilterChain chain)
              throws IOException,
                     ServletException{
        if (this.enable) {
            System.out.println(this + ": doFilter()") ;
            chain.doFilter(request, response);
        } else {
            // chain.doFilter(request, response); // 如果你发现页面始终是空白,问题就出在这里,不能缺少这行代码
        }
    }
    public void destroy(){
        // clean up
        System.out.println(this + ": destroy()");
    }
}

web.xml

  注意enable选项为false的时候,如果上面被注释掉的代码没取消注释,那么就会出问题,因为这里的url-pattern设置了此filter对站点的所有页面都要起作用

<filter> 
        <filter-name>simple-filterfilter-name> 
        <filter-class>org.foo.filterdemo.SimpleFilterfilter-class> 
        param> 
            <param-name>enableparam-name> 
            <param-value>trueparam-value> 
        param>
        param> 
            <param-name>refparam-name> 
            <param-value>这是一串中文,给SimpleFilter的param-value> 
        param>  
    filter>
    <filter-mapping>
        <filter-name>simple-filterfilter-name>
        /*
    

实际上,由于chain.doFilter()是不可缺少的,因此添加了enable参数的filter的代码应该这样写:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException{
        if (this.enable) {
            // do some work
        }
        chain.doFilter(request, response);
}

Article from “rldts” in “http://www.cnblogs.com/”
Original Article : http://www.cnblogs.com/qrlozte/p/3178454.html

Copyright rldts

你可能感兴趣的:(Web-Filter)