struts 2 <-- (contextloaderlistener) --> spring <-- (localsessionfactorybean) --> hibernate
这将要创建一个客户页面,以添加客户和列表的自定义函数。前端使用struts2显示,spring作为依赖注入引擎,而 hibernate 用来执行数据库操作。让我们开始...
在本章中,我们创建一个 ssh 的web工程,工程的目录结构如下图所示:
drop table if exists `h3`.`customer`; create table `h3`.`customer` ( `customer_id` bigint(20) unsigned not null auto_increment, `name` varchar(45) not null, `address` varchar(255) not null, `created_date` datetime not null, primary key (`customer_id`) ) engine=innodb auto_increment=17 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"> <!-- generated 20 julai 2010 11:40:18 am by hibernate tools 3.2.5.beta --> <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="create_date" length="19" not-null="true" /> </property> </class> </hibernate-mapping>
实现了 bo 和 dao 设计模式。所有bo和dao将由spring spring bean配置文件注入。在dao中,让它扩展spring的hibernatedaosupport来集成 spring 和 hibernate。
customerbo.java
package com.h3.customer.bo; import java.util.list; import com.h3.customer.model.customer; public interface customerbo{ void addcustomer(customer customer); list<customer> listcustomer(); }
customerboimpl.java
package com.h3.customer.bo.impl; import java.util.list; import com.h3.customer.bo.customerbo; import com.h3.customer.dao.customerdao; import com.h3.customer.model.customer; public class customerboimpl implements customerbo{ customerdao customerdao; //di via spring public void setcustomerdao(customerdao customerdao) { this.customerdao = customerdao; } //call dao to save customer public void addcustomer(customer customer){ customerdao.addcustomer(customer); } //call dao to return customers public list<customer> listcustomer(){ return customerdao.listcustomer(); } }
customerdao.java
package com.h3.customer.dao; import java.util.list; import com.h3.customer.model.customer; public interface customerdao{ void addcustomer(customer customer); list<customer> listcustomer(); }
customerdaoimpl.java
package com.h3.customer.dao.impl; import java.util.list; import org.springframework.orm.hibernate3.support.hibernatedaosupport; import com.h3.customer.dao.customerdao; import com.h3.customer.model.customer; public class customerdaoimpl extends hibernatedaosupport implements customerdao{ //add the customer public void addcustomer(customer customer){ gethibernatetemplate().save(customer); } //return all the customers in list public list<customer> listcustomer(){ return gethibernatetemplate().find("from customer"); } }
customeraction.java – struts2 的动作不再需要扩展actionsupport,它将由 spring 来处理。
package com.h3.customer.action; import java.util.arraylist; import java.util.date; import java.util.list; import com.h3.customer.bo.customerbo; import com.h3.customer.model.customer; import com.opensymphony.xwork2.modeldriven; public class customeraction implements modeldriven{ customer customer = new customer(); list<customer> customerlist = new arraylist<customer>(); customerbo customerbo; //di via spring public void setcustomerbo(customerbo customerbo) { this.customerbo = customerbo; } 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{ //save it customer.setcreateddate(new date()); customerbo.addcustomer(customer); //reload the customer list customerlist = null; customerlist = customerbo.listcustomer(); return "success"; } //list all customers public string listcustomer() throws exception{ customerlist = customerbo.listcustomer(); return "success"; } }
customerbean.xml – 声明 spring 的 bean:action, bo 和 dao.
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customeraction" class="com.h3.customer.action.customeraction"> <property name="customerbo" ref="customerbo" /> </bean> <bean id="customerbo" class="com.h3.customer.bo.impl.customerboimpl" > <property name="customerdao" ref="customerdao" /> </bean> <bean id="customerdao" class="com.h3.customer.dao.impl.customerdaoimpl" > <property name="sessionfactory" ref="sessionfactory" /> </bean> </beans>
database.properties – 声明数据库详细信息
jdbc.driverclassname=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://localhost:3306/h3 jdbc.username=root jdbc.password=password
datasource.xml – 创建一个数据库源的bean
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.config.propertyplaceholderconfigurer"> <property name="location"> <value>web-inf/classes/config/database/properties/database.properties</value> </property> </bean> <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="${jdbc.driverclassname}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> </beans>
hibernatesessionfactory.xml – 创建一个sessionfactory bean来集成spring和hibernate。
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- hibernate session factory --> <bean id="sessionfactory" class="org.springframework.orm.hibernate3.localsessionfactorybean"> <property name="datasource"> <ref bean="datasource"/> </property> <property name="hibernateproperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.mysqldialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingresources"> <list> <value>com/h3/customer/hibernate/customer.hbm.xml</value> </list> </property> </bean> </beans>
springbeans.xml – 创建一个核心 spring 的 bean 配置文件,作为中央的 bean 管理层。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- database configuration --> <import resource="config/spring/datasource.xml"/> <import resource="config/spring/hibernatesessionfactory.xml"/> <!-- beans declaration --> <import resource="com/h3/customer/spring/customerbean.xml"/> </beans>
customer.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>struts 2 + spring + 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="customeraction" method="addcustomer" > <result name="success">pages/customer.jsp</result> </action> <action name="listcustomeraction" class="customeraction" method="listcustomer" > <result name="success">pages/customer.jsp</result> </action> </package> </struts>
要集成struts2和spring,只需注册contextloaderlistener监听器类,定义一个“contextconfiglocation”参数要求spring容器来解析“springbeans.xml”,而不使用默认的“applicationcontext.xml”。
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> <context-param> <param-name>contextconfiglocation</param-name> <param-value>/web-inf/classes/springbeans.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.contextloaderlistener </listener-class> </listener> </web-app>
在浏览器中打开网址 : http://localhost:8080/ssh/listcustomeraction.action