81,091
社区成员
发帖
与我相关
我的任务
分享
在服务器启动时,就创建一个ServerContext
写一个实现ServletContextListener的类并且在web.xml部署下就OK了
package mypack;
import ....; //导入的自己写哈
public class MyServletContextListener implements ServletContextListener{
void contextDestroyed(ServletContextEvent sce){
ServletContext context = sce.getServletContext();
Configuration cfg = new Configuration().configure();
SessionFactory sf = config.buildSessionFactory();
context.setAttribute("sfName",sf);
}
void contextInitialized(ServletContextEvent sce){
}
}
在web.xml中在<servlet>标签开始之前加入如下标签:
<listener>
<listener-class>mypack.MyServletContextListener</listener-class>
</listener>
要别的地方 用的时候直接 SessionFactory sf = getServletContext.getAttribute("sfName");