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...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章