简介
在项目开发中,为了充分利用各个框架的优点,优势互补,常常将Struts2、Spring、Hibernate这三个框架整合使用。这个整合的过程也有多种,比如:是否使用hibernate.cfg.xml,是否使用注解等。本实例使用hibernate.cfg.xml和注解。
实例
Tools:Eclipse、MySQL、Struts2、Spring4、Hibernate3
1、导包。本实例所需基础jar包:单击下载。
2、项目目录和代码。项目结构如图1-1所示,代码也在下面一并列出。
图1-1 项目目录结构
@Namespace("/")
@ParentPackage("struts-default")
@Controller
public class StudentAction extends ActionSupport implements ModelDriven<Student> {
//封装数据
private Student student = new Student();
@Override
public Student getModel() {
return this.student;
}
@Autowired
private StudentService studentService;
@Action(value ="studentAction_add",results={@Result(name="add",location="/success.jsp")})
public String add(){
this.studentService.saveStudent(student);
return "add";
}
}
其中的注解:@Namespace(“/”)、@ParentPackage(“struts-default”)、@Action()代替了Struts.xml文件中的配置。
@Repository
public class StudentDaoImpl implements StudentDao {
//提供Hibernate模板
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public void save(Student student) {
this.hibernateTemplate.save(student);
}
@Override
public void update(Student student) {
this.hibernateTemplate.update(student);
}
@Override
public void delete(Student student) {
this.hibernateTemplate.delete(student);
}
@Override
public Student findById(Integer id) {
return this.hibernateTemplate.get(Student.class, id);
}
@Override
public List<Student> findAll() {
List<Student> students = null;
for(Object o:this.hibernateTemplate.find("from Student")){
students.add((Student)o);
}
return students;
}
}
项目中的两个接口文件代码没有列出,可根据实现类自行脑补。
@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer ID;
private Integer Sno;
private String Sname;
private String Saddress;
//属性的getter和setter方法省略......
//注解@Entity、@Table、@Id、@GeneratedValue代替了hibernate.hbm.xml
}
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Transactional
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Transactional
public void saveStudent(Student student) {
this.studentDao.save(student);
}
@Transactional
public void updateStudent(Student student) {
this.studentDao.update(student);
}
@Transactional
public void deleteStudent(Student student) {
this.deleteStudent(student);
}
@Transactional(readOnly = true)
public Student findStudentById(Integer id) {
return this.studentDao.findById(id);
}
@Transactional(readOnly = true)
public List<Student> findAllStudent() {
return this.studentDao.findAll();
}
}
其中注解@Transactional为Spring事务操作,在applicationContext.xml中也对事务进行了配置。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描 -->
<context:component-scan base-package="cn.jujianfei"></context:component-scan>
<!-- 1.配置SessionFactory -->
<bean id ="sessionFactory" class= "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 加载Hibernate核心配置文件 -->
<property name ="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 2.配置hibernate模板 -->
<bean id = "hibernateTemplate" class ="org.springframework.orm.hibernate3.HibernateTemplate">
<!-- 通过工厂获得session,操作PO类 -->
<property name ="sessionFactory" ref ="sessionFactory"></property>
</bean>
<!-- 事务管理 -->
<!-- #事务管理器,就是平台,Spring工具产生,依赖于使用持久方案 (hibernate/jdbc)等-->
<bean id ="txManager" class ="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name ="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 将事务管理注册Spring
* proxy-target-class ="true":使用cglib
* proxy-target-class="false" :有接口将使用JDK -->
<tx:annotation-driven transaction-manager="txManager" />
</beans>
hibernate.cfg.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 1.基本4项 -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/dbname
</property>
<property name="connection.username">root</property>
<property name="connection.password">jujianfei</property>
<!-- 2.方言 -->
<property name="dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 3.SQL -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 4.取消Bean校验 -->
<property name="javax.persistence.validation.mode">none</property>
<!-- 5.整合c3p0 -->
<property name="hibernate.conncetion.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<!-- 可以添加映射文件 -->
<mapping class="cn.jujianfei.domain.Student" />
</session-factory>
</hibernate-configuration>
web.xml配置
<!-- 监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- struts过滤器 -->
<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>
前台页面index.jsp
<body>
<form action="${pageContext.request.contextPath}/studentAction_add" method ="post">
学号:<input type ="text" name ="Sno" /><br>
姓名:<input type ="text" name ="Sname" /><br>
地址:<input type ="text" name ="Saddress"/><br>
<input type ="submit" value="添加" />
</form>
</body>
成功跳转页面success.jsp
<title>successPage</title>
</head>
<body>
添加成功!
</body>
</html>
总结
关于本实例的数据流向,我所理解的大致路线为:
1、前台表单提交数据(Sno,Sname,Saddress)
2、加载web.xml文件
3、StudentAction通过Struts2提供的模型驱动方式获取请求数据
4、调用StudentServiceImpl-->StudentDaoImpl-->数据库
5、StudentAction返回结果,页面跳转
// applicationContext.xml文件在其中属于运筹帷幄的角色,贯穿全局
在SSH整合的过程中,个人认为:Struts主要负责前后台数据的交互;Spring在中间控制协调控制,尤其是对实体类的管理;Hibernate负责对数据库的访问。对于Struts2的拦截器机制、值栈,Spring的事务、注解,Hibernate的缓存和数据检索等方面的知识,算是SSH的核心和重点 ,这些需要慢慢积累。