Servlet filter过滤RequestDispatcher.forward内部转发, 及FilterChain.doFilter的顺序

http://www.family168.com/tutorial/jsp/html/jsp-ch-07.html 

 

我们已经了解了filter的基本用法,还有一些细节配置在特殊情况下起作用。

在servlet-2.3中,Filter会过滤一切请求,包括服务器内部使用forward转发请求和<%@ include file="/index.jsp"%>的情况。

到了servlet-2.4中Filter默认下只拦截外部提交的请求,forward和include这些内部转发都不会被过滤,但是有时候我们需要forward的时候也用到Filter,这样就需要如下配置。

<filter>
    <filter-name>TestFilter</filtername>
    <filter-class>anni.TestFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>TestFilter</filtername>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>EXCEPTION</dispatcher>
</filter-mapping>
在tomcat5.5的web.xml最高应该是支持servlet2.4的...
----------------------------------
以Spring支持的OpenSessionInViewFilter为例,comment in blue.
 protected void doFilterInternal(
   HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
   throws ServletException, IOException {
  SessionFactory sessionFactory = lookupSessionFactory(request);
  boolean participate = false;
  if (isSingleSession()) {
   // single session mode
   if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
    // Do not modify the Session: just set the participate flag.
    participate = true;
   }
   else {
    logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
    Session session = getSession(sessionFactory);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
   }
  }
  else {
   // deferred close mode
   if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
    // Do not modify deferred close: just set the participate flag.
    participate = true;
   }
   else {
    SessionFactoryUtils.initDeferredClose(sessionFactory);
   }
  }
  try {
   filterChain.doFilter(request, response);
//如果还有其他filter则执行其他filter, 没有的话就执行jspServlet去了。 也就是说最后finally的在渲染view之后的。
  }
  finally {
   if (!participate) {
    if (isSingleSession()) {
     // single session mode
     SessionHolder sessionHolder =
       (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
     logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
     closeSession(sessionHolder.getSession(), sessionFactory);
    }
    else {
     // deferred close mode
     SessionFactoryUtils.processDeferredClose(sessionFactory);
    }
   }
  }
 }//Long term of session...

你可能感兴趣的:(Open,Source,filter,servlet,session,hibernate,include,spring)