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

  • 相关阅读:
    guake 3.4发布,支持切分窗口
    tmux下vim颜色不正常问题
    tmux下make menuconfig背景色不正常问题
    命令行工具PathMarker
    busybox syslog介绍
    linux下检测可用串口并使用minicom打开(改进版)
    linux下检测可用串口并使用minicom打开
    guake终端复制标签页
    shell命令行混合进制计算器smartbc
    在shell脚本中添加暂停,按任意键继续
  • 原文地址:https://www.cnblogs.com/hwgok/p/5356754.html
Copyright © 2011-2022 走看看