FirstFilter.java @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { System.out.println("Start.....doFilter----FirstFilter"); // arg2.doFilter(arg0, arg1); HttpServletRequest req = (HttpServletRequest) arg0; HttpServletResponse response2 = (HttpServletResponse) arg1; // 重定向 response2.sendRedirect(req.getContextPath() + "/main.jsp"); System.out.println("End.....doFilter----FirstFilter"); }
web.xml
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>com.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>/main.jsp</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
index.jsp
一个打印输出语句
<%
System.out.println("index.jsp");
%>
main.jsp
一个打印输出语句
<%
System.out.println("main.jsp");
%>
访问工程下面的index.jsp,控制台输出的结果是
Start.....doFilter----FirstFilter
End.....doFilter----FirstFilter
main.jsp
为什么不是先
main.jsp
后输出
End.....doFilter----FirstFilter
你可以把arg2.doFilter(arg0, arg1);的注释给去掉,然后你就会看到
因为你main.jsp对应的过滤器配置的是<dispatcher>FORWARD</dispatcher>,也就是说在执行main.jsp的时候并没有触发过滤器,所以说Start.....doFilter----FirstFilter和End.....doFilter----FirstFilter只是执行index.jsp触发的,执行完index.jsp的过滤器之后在加载main.jsp页面,所以最后才打印出main.jsp。这是我的理解,有可能有错误,还请大家多指点