首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts + Hibernate 整合全攻略:安裝、配置、Log4j、實戰代碼

     編輯:Java 相關知識

從環境搭建到代碼落地,完整記錄 Struts 1.1 + Hibernate 2.x 整合關鍵步驟,含 Resin/MySQL/JCreator/Dreamweaver 工具鏈、MiddleGen/Hibernate Extension 代碼生成、Log4j 初始化、Session 管理封裝、Action 協同範例。

一、環境棧

  • JDK 1.4+、Resin (輕量 Servlet 容器)、MySQL 4.0 (InnoDB 事務)
  • IDE:JCreator (輕量) / Eclipse、Dreamweaver MX 2004 + Struts Taglib 插件

二、Resin 虛擬主機配置

<host id="yourweb:8080" app-dir="e:\blog\" class-update-interval="2">
  <web-app id="/"><directory-servlet id="false"/></web-app>
  <error-log id="log/web-error.log"/>
</host>

三、Struts 核心配置 (web.xml + struts-config.xml)

拷貝 struts-*.tld 至 WEB-INF/,*.jar 至 WEB-INF/lib/。
ActionServlet 掛載 *.do,struts-config.xml 定義 FormBean、ActionMapping、Global Forward、MessageResource。

四、Hibernate 配置與代碼生成

1. hibernate.cfg.xml

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yourdatabase</property>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="transaction.factory_class">net.sf.hibernate.transaction.JDBCTransactionFactory</property>
<mapping resource="net/seerlog/hbm/Cat.hbm.xml"/>

2. MiddleGen 逆向生成 .hbm.xml

  • 配置 build.xml:JDBC URL、Driver、輸出目錄、Package 名。
  • 執行 ant → GUI 勾選表 → Generate → 產出映射檔。

3. hbm2java 生成 POJO

hbm2java c:\sample\org\hibernate\sample\*.xml --output=c:\sample\

修正 setenv.bat 中 JDBC_DRIVER、HIBERNATE_HOME、Classpath 實際 Jar。

五、Log4j 初始化 (ServletContextListener)

public class Log4jInitListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent e) {
        String path = e.getServletContext().getRealPath("/") + "/WEB-INF/classes/log4j.properties";
        PropertyConfigurator.configure(path);
    }
    public void contextDestroyed(ServletContextEvent e) {}
}

web.xml 註冊 Listener。
Action 中使用:static Logger log = Logger.getLogger("seerlog");

六、Hibernate Session 管理封裝 (ThreadLocal 模式)

public class HibernateUtil {
    private static final SessionFactory sf = new Configuration().configure().buildSessionFactory();
    private static final ThreadLocal tl = new ThreadLocal<>();

    public static Session getSession() throws HibernateException {
        Session s = tl.get();
        if (s == null) {
            Connection conn = DBConnectionManager.getConnection(); // 連接池
            s = sf.openSession(conn);
            tl.set(s);
        }
        return s;
    }
    public static void closeSession() throws HibernateException {
        Session s = tl.get();
        tl.set(null);
        if (s != null) s.close();
        // 歸還連接池...
    }
}

七、Action 協同範例

public class IndexAction extends Action {
    public ActionForward execute(ActionMapping m, ActionForm f,
                                 HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        try {
            Query q = session.createQuery("from Topic order by id desc");
            q.setMaxResults(5);
            List topics = q.list();
            req.setAttribute("newtopiclist", new NewTopicList(topics));
            tx.commit();
        } catch (HibernateException ex) {
            log.error(ex);
            tx.rollback();
        } finally {
            HibernateUtil.closeSession();
        }
        return m.findForward("index");
    }
}

八、struts-config.xml 關鍵片段

<action path="/index" type="net.seerlog.action.IndexAction" scope="request">
    <forward name="index" path="/first.jsp"/>
</action>
<action path="/login" name="loginForm" input="/login.jsp" scope="request">
    <forward name="success" path="/success.jsp"/>
</action>

九、總結

整合核心在於:
1. 統一 Session 生命週期 (ThreadLocal + 連接池)
2. 異常統一捕獲 → rollback → closeSession
3. 代碼生成工具鏈 (MiddleGen → hbm2java) 加速映射維護
4. Log4j 早期初始化,全程可追蹤

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved