利用 Struts PlugIn 機制,在應用啟動時初始化 Hibernate SessionFactory、綁定 JNDI,請求處理期間透過 ThreadLocal 管理 Session 生命週期,實現標準化整合模式。
public class HibernateSessionFactory {
private static final String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private final ThreadLocal threadLocal = new ThreadLocal();
private final Configuration cfg = new Configuration();
private SessionFactory sessionFactory;
public Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) session.close();
}
}
public class HibernatePlugin implements PlugIn {
private HibernateSessionFactory hsf = new HibernateSessionFactory();
private static final String JNDI_NAME = "jndi_hibernate_factory";
public void init(ActionServlet servlet, ModuleConfig config) {
bindFactoryToJNDI(); // 綁定 SessionFactory 到 JNDI
}
public void destroy() {
// 清理資源
}
private void bindFactoryToJNDI() {
try {
new InitialContext().bind(JNDI_NAME, hsf);
} catch (Exception e) { e.printStackTrace(); }
}
}
<plug-in className="zy.pro.td.plugin.HibernatePlugin" />
<plug-in className="zy.pro.td.plugin.HibernateSessionFactoryPlugIn" />
標準 ActionForm 實作,包含 username/password 屬性與驗證邏輯。
Context ctx = new InitialContext();
HibernateSessionFactory hsf = (HibernateSessionFactory) ctx.lookup("jndi_hibernate_factory");
Session session = hsf.currentSession();
// 執行資料庫操作...
此模式為 Struts 1.x 時代整合 Hibernate 的經典最佳實踐,亦為後續 Spring 管理 Hibernate 奠定概念基礎。