扩大作用域的范围我采用的技术是ThreadLocal类来实现
首先需要写一个过滤器
public class OpenSessionInView implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
Session session = HibUtil.getSession();//开启session
chain.doFilter(request, response);//放行
session.close(); //关闭session
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
在工具类中按如下写
public class HibUtil {
private static SessionFactory sessionFactory;
private static final ThreadLocal<Session> sessionThreadLocal = new ThreadLocal<Session>();
static{
//获取配置信息 hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
//创建一个 ServiceRegistry的实例
//首先获得其标准建造器,此处用了建造者模式 builder模式来创建对象
//创建一个标准的构建器
StandardServiceRegistryBuilder ssb = new StandardServiceRegistryBuilder();
//建造(得到)ServiceRegistry的实例此处一定要传入//configuration.getProperties()否则会报错UnsupportedOperationException
ServiceRegistry build = ssb.applySettings(configuration.getProperties()).build();
//获得session工厂 一个数据库对应一个 SessionFactory
sessionFactory = configuration.buildSessionFactory(build);
}
public static Session getSession(){
Session session = sessionThreadLocal.get();
if(session==null||!session.isOpen()){ //这样做的目的是确保每次获取的session是同一个
sessionThreadLocal.set(sessionFactory.openSession());
}
return sessionThreadLocal.get();
}
}
不要忘了在web.xml中配置
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>com.chdsxt.filter.OpenSessionInView</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
这样就能确保在service或dao层通过HibUtil.getSession()获取的session是同一个session,这样就达到了扩大作用域范围的要求