但是,当我们在a.jsp中request.getRequestDispathcer(“/b.jsp”).forward(request,response)时,就不会再执行过滤器了!也就是说,默认情况下,只能直接访问目标资源才会执行过滤器,而forward执行目标资源,不会执行过滤器!
public class MyFilter extends HttpFilter {
public void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("myfilter...");
chain.doFilter(request, response);
}
}
<filter>
<filter-name>myfilter</filter-name>
<filter-class>cn.itcast.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/b.jsp</url-pattern>
</filter-mapping>
<body>
<h1>b.jsp</h1>
</body>
<h1>a.jsp</h1>
<%
request.getRequestDispatcher("/b.jsp").forward(request, response);
%>
</body>
:8080/filtertest/b.jsp -->直接访问b.jsp时,会执行过滤器内容;
:8080/filtertest/a.jsp --> 访问a.jsp,但a.jsp会forward到b.jsp,这时就不会执行过滤器!
其实过滤器有四种拦截方式!分别是:REQUEST、FORWARD、INCLUDE、ERROR。
l REQUEST:直接访问目标资源时执行过滤器。包括:在地址栏中直接访问、表单提交、超链接、重定向,只要在地址栏中可以看到目标资源的路径,就是REQUEST;
l FORWARD:转发访问执行过滤器。包括RequestDispatcher#forward()方法、<jsp:forward>标签都是转发访问;
l INCLUDE:包含访问执行过滤器。包括RequestDispatcher#include()方法、<jsp:include>标签都是包含访问;
l ERROR:当目标资源在web.xml中配置为<error-page>中时,并且真的出现了异常,转发到目标资源时,会执行过滤器。
可以在<filter-mapping>中添加0~n个<dispatcher>子元素,来说明当前访问的拦截方式。
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/b.jsp</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/b.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/b.jsp</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>