问答详情
源自:5-1 [Java Web] 过滤器的分类1

内部转发为什么没有执行dofilter()方法

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方法

提问者:丶子非鱼 2017-05-04 11:43

个回答

  • 三爷JaVaja
    2017-07-20 14:00:08

    1)因为请求转发,地址不变还是index.jsp  即使Forward到了main.jsp 也不会起作用;

    这种情况除非你把main.jsp的监听改成Forward这样即使url不变,forward行为还是会被监听,然后又转发,死循环报错;

    2)因为请求重定向,所以地址会改变,然后监听器都会调用

  • 丶子非鱼
    2017-05-08 07:33:53

    过滤器名字可以和类不一样的

  • comeon5
    2017-05-06 02:13:56

    把 <filter-name>Filter</filter-name>统一改成<filter-name>firstFilter</filter-name>跟你的类名一致