使用filter导致服务器返回的页面始终是空白---在doFilter中漏写了chain.doFilter()
今天调代码的时候,突然发现,服务器开着,什么都没有问题,当我把下面这个filter给deploy了以后,访问所有的页面就都是空白。
后来发现,是因为在代码路径中,有一条路径没有调用filterChain.doFilter(request, response),想来也是,你这不就等于把HttpServletRequest给丢失了么
web.xml中,在enable="false"的情况下,会出现我上面描述的问题,代码如下
1 package org.foo.filterdemo ; 2 3 import java.io.* ; 4 5 import javax.servlet.* ; 6 7 public class SimpleFilter implements Filter { 8 9 private boolean enable = false; 10 11 public void init(FilterConfig config) 12 throws ServletException{ 13 String enableString = config.getInitParameter("enable"); 14 if (enableString != null && enableString.equalsIgnoreCase("true")) { 15 this.enable = true; 16 } 17 String initParam = config.getInitParameter("ref") ; 18 try { 19 initParam = new String(initParam.getBytes("iso-8859-1"), "UTF-8"); 20 } catch (UnsupportedEncodingException e) { 21 e.printStackTrace(); 22 } 23 System.out.println(this + ": init(), init-param = " + initParam); 24 } 25 public void doFilter(ServletRequest request, 26 ServletResponse response, 27 FilterChain chain) 28 throws IOException, 29 ServletException{ 30 if (this.enable) { 31 System.out.println(this + ": doFilter()") ; 32 chain.doFilter(request, response); 33 } else { 34 // chain.doFilter(request, response); // 如果你发现页面始终是空白,问题就出在这里,不能缺少这行代码 35 } 36 } 37 public void destroy(){ 38 // clean up 39 System.out.println(this + ": destroy()"); 40 } 41 }
web.xml
注意enable选项为false的时候,如果上面被注释掉的代码没取消注释,那么就会出问题,因为这里的url-pattern设置了此filter对站点的所有页面都要起作用
1 <filter> 2 <filter-name>simple-filter</filter-name> 3 <filter-class>org.foo.filterdemo.SimpleFilter</filter-class> 4 <init-param> 5 <param-name>enable</param-name> 6 <param-value>true</param-value> 7 </init-param> 8 <init-param> 9 <param-name>ref</param-name> 10 <param-value>这是一串中文,给SimpleFilter的</param-value> 11 </init-param> 12 </filter> 13 <filter-mapping> 14 <filter-name>simple-filter</filter-name> 15 <url-pattern>/*</url-pattern> 16 </filter-mapping>
实际上,由于chain.doFilter()是不可缺少的,因此添加了enable参数的filter的代码应该这样写:
1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 2 throws IOException, ServletException{ 3 if (this.enable) { 4 // do some work 5 } 6 chain.doFilter(request, response); 7 }