把hibernate用到的包全部放進web應用程序的lib裡面,然後定義hibernate.cfg.XML,也就是插件的配置信息,如下
信息很清楚的,就是配置數據庫等信息,我們利用jndi來查找SessionFactory,下面是插件程序,HibernatePlugIn.Java
import org.apache.struts.action.PlugIn;import org.apache.struts.action.ActionServlet;import org.apache.struts.config.ModuleConfig;import javax.servlet.ServletException;import Javax.servlet.ServletContext;import net.sf.hibernate.SessionFactory;import net.sf.hibernate.cfg.Configuration;public class HibernatePlugIn implements PlugIn { public void destroy() { } public void init(ActionServlet servlet, ModuleConfig config) throws ServletException { try { ServletContext context = servlet.getServletContext(); SessionFactory sf = new Configuration().configure().buildSessionFactory(); context.setAttribute("net.sf.hibernate.SessionFactory",sf); } catch (Exception ex) { ex.printStackTrace(); } }}相應的,要在struts-config.XML配置插件信息,大概如下,注意路徑
以後就可以利用java.naming.Context,Java.naming.InitiaContext來查找
Context ct = new InitialContext(); sessions=(SessionFactory) ct.lookup("hibernate/session_factory"); session=sessions.openSession();
當然,還有另外兩種整合方式,我認為這種方法更為靈活,也比較容易掌握