public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("start----doFilter--FirstFilter");
//chain.doFilter(request, response);
HttpServletRequest req =(HttpServletRequest) request;
HttpServletResponse response2 =(HttpServletResponse) response;
//重定向
// response2.sendRedirect(req.getContextPath()+"/index.jsp");
//转发
req.getRequestDispatcher("index.jsp").forward(request, response);
// req.getRequestDispatcher("main.jsp").include(request, response);
System.out.println("end------doFilter--FirstFilter");
}
配置文件:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Filter</filter-name>
<filter-class>FirstFilter.firstFilter</filter-class>
</filter>
<!--
<filter-mapping>
<filter-name>Filter</filter-name>
<url-pattern>/index.jsp</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
-->
<filter-mapping>
<filter-name>Filter</filter-name>
<url-pattern>/index.jsp</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
</web-app>
控制台执行了init() 但是执行index.jsp并没有打印dofilter方法
1)因为请求转发,地址不变还是index.jsp 即使Forward到了main.jsp 也不会起作用;
这种情况除非你把main.jsp的监听改成Forward这样即使url不变,forward行为还是会被监听,然后又转发,死循环报错;
2)因为请求重定向,所以地址会改变,然后监听器都会调用
过滤器名字可以和类不一样的
把 <filter-name>Filter</filter-name>统一改成<filter-name>firstFilter</filter-name>跟你的类名一致