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

  • 相关阅读:
    北斗授时服务器,时间同步服务器,网络时钟服务器2020最新报价
    北斗GPS卫星同步时钟让采集系统更精准
    ntp时钟服务器(医院时钟系统)在网络里的作用
    「Excel技巧」Excel中根据某列的值去汇总另外一列的值
    「Excel技巧」Excel技巧之如何看文件里的宏?
    「杂谈」同学聚会最悲哀的事情
    torch 中的损失函数
    CJJ/T 302-2019 城市园林绿化监督管理信息系统工程技术标准
    SJ/T 11362-2006 企业信息化技术规范 制造执行系统(MES)规范
    1. C语言三个数从小到大排序/输出
  • 原文地址:https://www.cnblogs.com/hwgok/p/5356754.html
Copyright © 2011-2022 走看看