第一次用Struts PlugIn请指点一下。
PlugIn的代码如下:
package com.yourcompany.struts;
import javax.servlet.ServletException;import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;public class HibernatePlugIn implements PlugIn{
public String path;
public static SessionFactory sessionFactory;
public void destroy() {
// TODO 自动生成方法存根
sessionFactory.close();
} public void init(ActionServlet arg0, ModuleConfig arg1) throws ServletException {
// TODO 自动生成方法存根
Configuration cfg = new Configuration();
cfg.configure(path);
sessionFactory = cfg.buildSessionFactory(); } public static SessionFactory getSessionFactory() {
return sessionFactory;
} public String getPath() {
return path;
} public void setPath(String path) {
this.path = path;
}
}
按照Struts PlugIn的原理,在启动容器时就会按配置文件生成HibernatePlugIn的实例调用init()为静态变量 sessionFactory赋值,当关闭容器
时在调用destroy() 释放资源!HibernatePlugIn实例的生命周期也就是从容器启动到关闭,那静态变量 sessionFactory被赋值了就一真存在,为什么我HibernatePlugIn的生命周期中在其他类中HibernatePlugIn.getSessionFactory() 获取的值为null呢?

解决方案 »

  1.   

    path值是在STRUTS的配置文件中取值。
    <plug-in
       className="com.yourcompany.struts.HibernatePlugIn">
    <set-property value="/hibernate.cfg.xml" property="path" ></set-property>
    </plug-in>把我搞伤心了,又试了一下在HibernatePlugIn中添加静态变量public static int age=25;然后在容器启动后
    在其他的类里用System.out.print(HibernatePlugIn.age)。一点问题都没有输出“25”。为什么HibernatePlugIn.sessionFactory是null?
      

  2.   

    意识是你的连接瓷为空?Session session = HibernaterSessionFactory.getSession();你答应看看能不能取的session对象!
      

  3.   

    如果能回去session那么  连接吃不可能为空吧`!
      

  4.   

    修改init()进行测试,如下。
    public void init(ActionServlet arg0, ModuleConfig arg1) throws ServletException { 
    // TODO 自动生成方法存根 
    Configuration cfg = new Configuration(); 
    cfg.configure(path); 
    sessionFactory = cfg.buildSessionFactory(); 
         if (sessionFactory==null)
             System.out.print(null);
          else
             System.out.print(not null);
    } 控制台输出“not null”,证明这里sessionFactory 是取得了值的。
      

  5.   

    顶  5楼  
    sessionFactory是在init方法中创建的,而最终的结果为null,那就说明cfg在调用buildSessionFactory()方法时没有成功创建sessionFactory.再往上推一步,那就是说cfg.configure(path)可能有问题,建议在此处短点,看看path是否拿到了struts中path的值. 如果没有值,那就说明你的配置写错了,仔细检查,如果有,那就说明你的代码写过了
    不应该这样写:
    Configuration cfg = new Configuration(); 
    cfg.configure(path); 
    sessionFactory = cfg.buildSessionFactory(); 
    以上只是分析..
    具体怎样写不知道.....