建立一个Web项目,然后导入如下包
l struts2包:在struts2-blank.war下的lib目录下,以及struts-2.3.15.1\lib下的struts和spring整合的插件包struts2-spring-plugin-2.3.15.1.jar
l hibernate包:hibernate-distribution-3.6.10.Final\lib\,把required中的所有包都导入进去,以及jpa下的hibernate-jpa-2.0-api-1.0.1.Final,optional/ c3p0下的JDBC连接池c3p0-0.9.1.jar包,MYSQL的jdbc驱动mysql-connector-java-5.1.7-bin, hibernate的的一个日志系统,hibernate3.jar。
l spring2.5:spring
在hibernate-distribution-3.6.10.Final\project\etc下找到一个hibernate.cfg.xml文件,拷贝到项目中的src下,去掉没用的部分。
添加applicationContext.xml文件。
1、整合SHH
首先整合spring和hibernate
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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.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">
<!-- 自动扫描与装配bean -->
<context:component-scan base-package="cn.itcast.oa"></context:component-scan>
<!-- 配置SessionFactory(与Hibernate整合) -->
<!-- 表示下面的变量是从这个配置文件读取的 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 在spring中配置了一个叫sessionFactory的bean,类为hibernate中的LocalSessionFactoryBean,这样,spring就和hibernate联系起来了 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 指定hibernate的配置文件的位置,classpath:hibernate.cfg.xml:配置文件的路径 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property><!-- -->
<property name="dataSource">
<!-- 配置DataSource数据源,这里采用的是c3p0的数据库连接 -->
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="user" value="${username}"></property>
<property name="password" value="${password}"></property>
<!-- 其他配置 ,具体可以参考c3p0的文档-->
<property name="initialPoolSize" value="3"></property>
<property name="minPoolSize" value="3"></property>
<property name="maxPoolSize" value="15"></property>
<property name="acquireIncrement" value="3"></property>
<property name="maxStatements" value="8"></property>
<property name="maxStatementsPerConnection" value="5"></property>
<property name="maxIdleTime" value="1800"></property>
</bean>
</property>
</bean>
<!-- 配置声明式事物,使用基于注解的方式 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 声明式事物管理, 告诉他事物管理是哪一个(transactionManager)-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
配置hibernate.cfg.xml文件
<!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>
<!-- 数据库信息 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 连接数据库的配置文件写到applicationContext.xml文件中
<property name="connection.url">jdbc:mysql:///OA</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
-->
<!-- 声明映射的配置文件 -->
<mapping resource="cn/itcast/oa/domain/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
Jdbc.properties文件
jdbcUrl=jdbc:mysql:///OA
driverClass=com.mysql.jdbc.Driver
username=root
password=root
到目前为止,我们已经把Hibernate和Spring的框架搭好了,现在我们来做一些测试
建立TestSpring类,这个类用于测试Spring和Hibernate是否整合成功
public class TestSpring {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
@Test//执行这个测试方法时,会自动生成数据库中的表
public void testSessionFactory(){
//从applicationContext.xml中获取名为sessionFactory的这个bean
SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
System.out.println(sessionFactory.openSession());//打开session
}
@Test
public void addUser(){
TestService testService = (TestService) ac.getBean("testService");
testService.addUser();
}
}
成功时会打印如下信息:
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];
ActionQueue[insertions=[] updates=[]deletions=[]
collectionCreations=[] collectionRemovals=[]collectionUpdates=[]])
第二个方法addUser用于测试事物是否能够有效执行
public class User {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
User.hbm.xml
<hibernate-mapping package="cn.itcast.oa.domain">
<!-- 配置的是User对象,对应的表为userTable -->
<class name="User" table="user_Table">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
//@Component相当于在applicationContext中的bean,在bean中,我们添加了bean的id名称
//这里我们也可以使用默认名称(当前类名,首字母小写--testService),也可以添加他的名称
//别名:@Component("别名")
@Component//把TestService作为bean注入到spring容器中
public class TestService {
@Resource//把sessionfactory注入到spring容器中
private SessionFactory sessionFactory;
@Transactional
public void addUser(){
Session session = sessionFactory.getCurrentSession();
session.save(new User());
// int a=1/0;//执行到这一步时,由于分母为零,异常,因此回滚,但是数据表中的id字段会增加1
session.save(new User());
}
}
先注释掉int a=1/0;执行,去掉注释执行,在注释执行,得到如下结果:
说明当遇到a=1/0之前添加了一个User,执行到a=1/0时,异常回滚了
到目前为止,我们已经成功整合了hibernate和spring,下面我们将整合spring和struts。
在整合的过程中,启动tomcat时,我们遇到了如下的错误提示:
Exception starting filter struts2
Unable to load configuration. - bean - jar:file:/D:/Program%20Files/Apache%20Software%20Foundation/Tomcat%206.0/webapps/SSH/WEB-INF/lib/struts2-core-2.3.15.1.jar!/struts-default.xml:68:184
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:502)
提示的消息是说不能加载struts2-core-2.3.15.1.jar/struts-default.xml这个配置文件。
解决:
由于版本的不一致,我们在发布的时候导致了出现同一个文件的不同版本,我这里是出现了struts2-core-2.3.15.1.jar和struts2-core-2.3.8.jar这两个文件同时在项目中,如果只在项目中删除的话,不一定能够完全删除,需要在D:\Program Files\Apache Software Foundation\Tomcat6.0\webapps\SSH\WEB-INF\lib下删除其中的一个文件,我这里删除的是struts2-core-2.3.15.1.jar,我如果删除struts2-core-2.3.8.jar,貌似也会出现问题?可能是版本不一致的原因,不懂。。。
//这个bean的生命周期默认值为singleton(单例),但是这里由于每个bean返回的是一个实例,
//所以不能使用singleton模式,代表每次返回一个action的实例
@Scope("prototype")
// @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
// @Service 通常作用在业务层,但是目前该功能与 @Component 相同。
// @Constroller 通常作用在控制层,但是目前该功能与 @Component相同。
@Controller
public class TestAction extends ActionSupport {
@Resource
//把testService作为bean注入到spring容器中
private TestService testService;
public String execute() throws Exception {
System.out.println("TestAction.execute()");
testService.addUser();
return "success";
}
}
Struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" /><!-- 设置为开发模式 -->
<package name="default" namespace="/" extends="struts-default">
<!-- Struts2与Spring整合后,class属性中写的是bean的名称 -->
<action name="testAction" class="testAction">
<result name="success">/test.jsp</result>
</action>
</package>
<!-- Add packages here -->
</struts>
最后一步:整合spring和web.xml,也就是需要对web.xml文件做一下配置,如下所示:
<!--
ContextLoaderListener的作用就是启动Web容器时,
自动装配ApplicationContext的配置信息。
因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,
启动容器时,就会默认执行它实现的方法。
在ContextLoaderListener中关联了ContextLoader这个类,
所以整个加载配置过程由ContextLoader来完成。
applicationContext.xml的文件位置就可以有两种默认实现:
第一种:直接将之放到/WEB-INF下,之在web.xml中声明一个listener
第二种:将之放到classpath下,但是此时要在web.xml中加入<context-param>,
用它来指明你的applicationContext.xml的位置以供web容器来加载。
按照 Struts2 整合spring的官方给出的档案,写成:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml
</param-value>
</context-param>
-->
===========================这是添加的内容=============================
<!-- 把spring交给web.xml,配置spring的初始化监听器ContextLoaderListener -->
<listener>
<listener-class>
<!-- 执行这句话时,会自动装配ApplicationContext(Spring) -->
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
====================================================================
<!-- 从struts2中的
配置Struts2的过滤器
-->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
测试的页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
Spring和struts2整合成功。
</body>
</html>
测试成功的页面: