Struts2+Hibernate集成實例
在 Struts2 中,沒有官方的插件集成Hibernate框架。但是,可以通過以下步驟解決方法:
- 註冊一個自定義的 ServletContextListener
- 在 ServletContextListener 類, 初始化Hibernate會話,並將其存儲到servlet上下文。
- 在動作類, 可以通過servlet上下文的Hibernate會話,並執行任務正常的Hibernate操作。
請參閱它們的關係:
Struts 2 <-- (Servlet Context) ---> Hibernate <-----> Database
在本教程中,在Struts中2開發我們顯示了一個簡單的客戶模塊(添加和列表功能),並使用 Hibernate 進行數據庫操作。使用上述部分機制集成(存儲和檢索在servlet上下文Hibernate的Session)。
1. 工程目錄結構
來看看這個完整的項目文件夾結構。
2. MySQL表結構腳本
創建一個客戶(customer)表。下面是SQL表腳本。
CREATE TABLE `customer` (
`customer_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`address` varchar(255) NOT NULL,
`create_date` datetime NOT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
4. Hibernate 相關配置
Hibernate的模型和配置的東西。
Customer.java – 創建客戶表對應的一個類。
package com.yiibai.customer.model;
import java.util.Date;
public class Customer implements java.io.Serializable {
private Long customerId;
private String name;
private String address;
private Date createdDate;
//getter and setter methods
}
Customer.hbm.xml – Hibernate映射文件客戶表。
<id name="customerId" type="java.lang.Long">
<column name="CUSTOMER\_ID" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="NAME" length="45" not-null="true" />
</property>
<property name="address" type="string">
<column name="ADDRESS" not-null="true" />
</property>
<property name="createdDate" type="timestamp">
<column name="CREATED\_DATE" length="19" not-null="true" />
</property>
</class>
hibernate.cfg.xml – Hibernate數據庫配置文件
5. Hibernate ServletContextListener
創建一個類 ServletContextListener, 並初始化Hibernate會話,並將其存儲到servlet上下文。
HibernateListener .java
package com.yiibai.listener;
import java.net.URL;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateListener implements ServletContextListener{
private Configuration config;
private SessionFactory factory;
private String path = "/hibernate.cfg.xml";
private static Class clazz = HibernateListener.class;
public static final String KEY\_NAME = clazz.getName();
public void contextDestroyed(ServletContextEvent event) {
//
}
public void contextInitialized(ServletContextEvent event) {
try {
URL url = HibernateListener.class.getResource(path);
config = new Configuration().configure(url);
factory = config.buildSessionFactory();
//save the Hibernate session factory into serlvet context
event.getServletContext().setAttribute(KEY\_NAME, factory);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
在 web.xml 文件中註冊監聽器。
web.xml
6. Action
在動作類, 可以通過servlet上下文的Hibernate會話和執行正常的Hibernate任務。
CustomerAction.java
package com.yiibai.customer.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.yiibai.customer.model.Customer;
import com.yiibai.listener.HibernateListener;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class CustomerAction extends ActionSupport
implements ModelDriven{
Customer customer = new Customer();
List<Customer> customerList = new ArrayList<Customer>();
public String execute() throws Exception {
return SUCCESS;
}
public Object getModel() {
return customer;
}
public List<Customer> getCustomerList() {
return customerList;
}
public void setCustomerList(List<Customer> customerList) {
this.customerList = customerList;
}
//save customer
public String addCustomer() throws Exception{
//get hibernate session from the servlet context
SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext()
.getAttribute(HibernateListener.KEY\_NAME);
Session session = sessionFactory.openSession();
//save it
customer.setCreatedDate(new Date());
session.beginTransaction();
session.save(customer);
session.getTransaction().commit();
//reload the customer list
customerList = null;
customerList = session.createQuery("from Customer").list();
return SUCCESS;
}
//list all customers
public String listCustomer() throws Exception{
//get hibernate session from the servlet context
SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext()
.getAttribute(HibernateListener.KEY\_NAME);
Session session = sessionFactory.openSession();
customerList = session.createQuery("from Customer").list();
return SUCCESS;
}
}
7. JSP 頁面
JSP頁面用來添加和列出的客戶。
customer.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts 2 + Hibernate integration example
Add Customer
All Customers
<s:if test="customerList.size() > 0">
Customer Id | Name | Address | Created Date |
---|---|---|---|
8. struts.xml
<action name="addCustomerAction"
class="com.yiibai.customer.action.CustomerAction" method="addCustomer" >
<result name="success">pages/customer.jsp</result>
</action>
<action name="listCustomerAction"
class="com.yiibai.customer.action.CustomerAction" method="listCustomer" >
<result name="success">pages/customer.jsp</result>
</action>
9. 實例測試執行
訪問客戶模塊:http://localhost:8080/struts2hibernate/listCustomerAction.action
在名稱和地址字段填寫,點擊提交按鈕,插入的客戶的詳細信息會馬上列出結果。
參考
- Struts2 + Hibernate使用「Full Hibernate Plugin"集成
- ServletContextListener 文檔
- Struts + Hibernate集成實例