zoukankan      html  css  js  c++  java
  • 扩大作用域的范围

    扩大作用域的范围我采用的技术是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,这样就达到了扩大作用域范围的要求

  • 相关阅读:
    面试笔试题目集
    [vs2010]:fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "StdAfx.h"”?
    [数据库] SQLite常见问题解答
    安卓学习资料总结39
    Android 学习资料总结40
    python变量的定义和使用
    python运算符
    python的注释
    print输出函数
    python数据类型转换
  • 原文地址:https://www.cnblogs.com/hwgok/p/5356754.html
Copyright © 2011-2022 走看看