最近正在学习ssh的最新版本。由于一直没有用ssh做过东西,尤其是中间的spring,项目中用到的struts和hibernate,所以对于在中间层加上spring该如何处理,还存在一些困惑,这是我做的一个三者结合的例子,其主要目的是充分利用spring的ioc和hibernate3的annoation
1.struts2和spring的结合,以及如何把action纳入spring的管理
首先:工程中应加入struts2-spring-plugin-2.0.8.jar
其次:在web.xml中加入如下
org.springframework.web.context.ContextLoaderListener
第三:在struts.xml和applicationContext.xml中的配置如下
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<action name="Login" class="Login" method="getAllUserInfo">
applicationContext.xml中(配置片段)
注意”红色“字体部分,其中action中的class=“Login”要和
ok,struts2和spring已经结合到一起,剩下的就是根据项目需要"求精了"
2,spring和hibernate的结合hibernate3 aonotation
目前的例子只是演示如何集成二者,所以只是将hibernte的SessionFactory交由spring管理,其他的如(事务管理没有考虑很细致,全部在dao层控制)
如下applicationContext.xml
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
default-lazy-init="true" default-autowire="autodetect">
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/paulstudy" p:username="root"
p:password="1234" />
org.hibernate.dialect.SQLServerDialect
通过以上实现了hibernate的零配置文件。如下domainobject
package com.model;
import javax.persistence.Column;//所在jar包是 persistence-api-1.0.jar
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Entity;
import org.hibernate.annotations.AccessType;
//import org.hibernate.annotations.Entity;
import org.hibernate.annotations.GenericGenerator;
@Entity//此处声明必须用avax.persistence.Entity;而不能用 org.hibernate.annotations.Entity
@Table(name = "userinfo")
@AccessType("property")
public class UserInfo {
private String userId = "";
private String userName = "";
private String userSex = "";
private int userAge = 0;
@Id
@Column(name = "userid")
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Column(name = "username")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "usersex")
public String getUserSex() {
return userSex;
}
@Column(name = "userage")
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
}
ok。spring和hibernate的结合,hibernate的零配置已经搞定,很简单吧
学好。学精还需要时间啊!