整合struts与hibernate
使用struts的plugin机制将Hibernate配置进去,下面转贴一篇说明的文章
1、建立一个Class,HibernatePlugIn 放在src下
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
public class HibernatePlugIn implements PlugIn {
public void destroy() {
}
public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {
try{
ServletContext context = null;
context = servlet.getServletContext();
SessionFactory sf = new Configuration().configure().
buildSessionFactory();
context.setAttribute("net.sf.hibernate.SessionFactory", sf);
}
catch(Exception e){
e.printStackTrace();
}
}
}
2、在struts-config.xml中添加
3、将hibernate.cfx.xml放在src目录下,并且属性设为copy
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
这样以后就可以在任何地方调用了
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
import javax.naming.InitialContext;
import javax.naming.Context;
public class MyService {
private SessionFactory sf;
public LoginService() throws Exception {
Context ctx = new InitialContext();
sf = (SessionFactory) ctx.lookup("hibernate/session_factory");
}
}

Leave a comment