Spring OpenSessionInViewFilter

OpenSessionInViewFilter类实现,其继承OncePerRequestFilter
通过执行doFilter链,每次请求是打开当前线程绑定的session,如果没有则新建;每个请求只有一个session。
 protected boolean isSingleSession() {
		return this.singleSession;//默认true
	}

 @Override
 protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
                //获取sessionFactory
		SessionFactory sessionFactory = lookupSessionFactory(request);
		boolean participate = false;

		if (isSingleSession()) {
                        //判断当前请求资源中是否有已有session
			// 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 session = getSession(sessionFactory);

	                       //将session绑定到当前请求的线程池中
			 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
			}
		}
		else {
                         //延迟关闭session
			// 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
		}

		finally {
                        //请求处理完成关闭session
			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);
				}
			}
		}
	}


OncePerRequestFilter类的doFilter
 public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		........//request的处理
		if (request.getAttribute(alreadyFilteredAttributeName) != null || shouldNotFilter(httpRequest)) {
			// Proceed without invoking this filter...
			filterChain.doFilter(request, response);
		}
		else {
			// Do invoke this filter...
			request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
			try {
				[color=red]doFilterInternal(httpRequest, httpResponse, filterChain);//调用其实现的方法OpenSessionInViewFilter[/color]
			}
			finally {
				// Remove the "already filtered" request attribute for this request.
				request.removeAttribute(alreadyFilteredAttributeName);
			}
		}
	}

你可能感兴趣的:(Spring OpenSessionInViewFilter)