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);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值