struts 2 <-- (servlet context) ---> hibernate <-----> database
在本教程中,在struts中2开发我们显示了一个简单的客户模块(添加和列表功能),并使用 hibernate 进行数据库操作。使用上述部分机制集成(存储和检索在servlet上下文hibernate的session)。
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;
customer.java – 创建客户表对应的一个类。
package com.h3.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映射文件客户表。
<?xml version="1.0"?>
<!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.h3.customer.model.customer"
table="customer" catalog="h3">
<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-mapping>
hibernate.cfg.xml – hibernate数据库配置文件
<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-configuration public
"-//hibernate/hibernate configuration dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/h3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.mysqldialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">false</property>
<mapping resource="com/h3/customer/hibernate/customer.hbm.xml" />
</session-factory>
</hibernate-configuration>
创建一个类 servletcontextlistener, 并初始化hibernate会话,并将其存储到servlet上下文。
hibernatelistener .java
package com.h3.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
<!doctype web-app public
"-//sun microsystems, inc.//dtd web application 2.3//en"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>struts 2 web application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>
com.h3.listener.hibernatelistener
</listener-class>
</listener>
</web-app>
在动作类, 可以通过servlet上下文的hibernate会话和执行正常的hibernate任务。
customeraction.java
package com.h3.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.h3.customer.model.customer;
import com.h3.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;
}
}
customer.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>struts 2 + hibernate integration example</h1> <h2>add customer</h2> <s:form action="addcustomeraction" > <s:textfield name="name" label="name" value="" /> <s:textarea name="address" label="address" value="" cols="50" rows="5" /> <s:submit /> </s:form> <h2>all customers</h2> <s:if test="customerlist.size() > 0"> <table border="1px" cellpadding="8px"> <tr> <th>customer id</th> <th>name</th> <th>address</th> <th>created date</th> </tr> <s:iterator value="customerlist" status="userstatus"> <tr> <td><s:property value="customerid" /></td> <td><s:property value="name" /></td> <td><s:property value="address" /></td> <td><s:date name="createddate" format="dd/mm/yyyy" /></td> </tr> </s:iterator> </table> </s:if> <br/> <br/> </body> </html>
<?xml version="1.0" encoding="utf-8" ?>
<!doctype struts public
"-//apache software foundation//dtd struts configuration 2.0//en"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devmode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="addcustomeraction"
class="com.h3.customer.action.customeraction" method="addcustomer" >
<result name="success">pages/customer.jsp</result>
</action>
<action name="listcustomeraction"
class="com.h3.customer.action.customeraction" method="listcustomer" >
<result name="success">pages/customer.jsp</result>
</action>
</package>
</struts>
访问客户模块:http://localhost:8080/struts2hibernate/listcustomeraction.action


