一、整合SSH 基于注解的方式
准备:
配置struts2,和hibernate环境 单独测试struts2
所需jar包:
antlr-2.7.6.jar
aspectjrt.jar
aspectjweaver.jar
backport-util-concurrent.jar
c3p0-0.9.1.jar
cglib-nodep-2.1_3.jar
commons-codec-1.3.jar
commons-collections-3.1.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging-1.0.4.jar
commons-logging-1.1.1.jar
commons-logging.jar
dom4j-1.6.1.jar
ehcache-1.5.0.jar
freemarker-2.3.15.jar
hibernate3.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
junit-4.4.jar
log4j.jar
mysql-connector-java-5.1.10-bin.jar
ognl-2.7.3.jar
slf4j-api-1.5.8.jar
slf4j-log4j12.jar
spring.jar
struts2-core-2.1.8.1.jar
struts2-spring-plugin-2.1.8.1.jar
xwork-core-2.1.6.jar
a, 整合Spring与Hibernate
目的:
让Spring管理单例的SessionFactory
让Spring管理事务(采用基于注解的方式) 测试事务
步骤:
1.1 引入外部的数据库连接信息配置文件
1.2 配置C3P0数据源(数据库连接池)信息
1.3 spring整合hibernate配置sessionFactory的方式 默认单例模式
1.4 配置声明式的事务管理(采用基于注解的形式)
测试SessionFactory
b, 整合Spring与Struts2
目的:
让Spring管理Action的实例(多例),这样就可以方便的注入依赖的对象了。
步骤:
1,Spring在Web应用中使用时要在web.xml中配置一个监听器,为了创建ApplicationContext对象
2,添加struts2-spring-plugin.jar,为了让Struts2从Spring的容器中拿Action对象
二、所需配置如下:
1. web.xml
-----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置spring用于初始化ApplicationContext对象的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<!-- 配置用于初始化工作的监听器 注:要放到spring的ContextLoaderListener监听器后面,因为要用到其创建的spring容器对象
<listener>
<listener-class>cn.itcast.oa.util.OAInitListener</listener-class>
</listener>
-->
<!-- 配置Spring的OpenSessionInViewFilter以解决懒加载异常的问题 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<!-- 配置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>
</web-app>
-----------------------------------------------------------------------------------------
2. struts.xml
-----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<!-- 配置为开发模式自动加载配置文件 -->
<constant name="struts.devMode" value="true"></constant>
<!-- 把action的扩展名改为.do 注: value的值不要加点,直接写扩展名即可 -->
<constant name="struts.action.extension" value="do"></constant>
<!-- 将主题设为simple -->
<constant name="struts.ui.theme" value="simple"></constant>
<!-- 引入子配置文件 -->
<package name="default" namespace="/" extends="struts-default">
<!-- 声明拦截器
<interceptors>
<interceptor name="checkPrivilege" class="cn.itcast.oa.util.CheckPrivilegeInterceptor"></interceptor>
<!-- 配置默认的拦截器栈 -->
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="checkPrivilege"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
-->
<!-- 定义全局结果页面
<global-results>
<result name="loginUI">/WEB-INF/jsp/loginoutAction/loginUI.jsp</result>
<result name="noPrivilegeUI">/noPrivilegeUI.jsp</result>
</global-results>
-->
<!-- 引入子配置文件 -->
<!-- 例子:岗位管理
<action name="role_*" class="roleAction" method="{1}">
<result name="list">/WEB-INF/jsp/roleAction/list.jsp</result>
<result name="saveUI">/WEB-INF/jsp/roleAction/saveUI.jsp</result>
<result name="setPrivilegeUI">/WEB-INF/jsp/roleAction/setPrivilegeUI.jsp</result>
<result name="toList" type="redirectAction">role_list</result>
</action>
-->
</package>
</struts>
-----------------------------------------------------------------------------------------
3.hibernate.cfg.xml
-----------------------------------------------------------------------------------------
<?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>
<!-- 数据库连接信息 注:在spring中配置C3P0数据源信息 ,hibernate自带的连接池性能不好-->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</property>
<!-- 其他配置信息 -->
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<!-- 加载映射文件 -->
<mapping resource="cn/itcast/oa/domain/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
-----------------------------------------------------------------------------------------
4.POJO.hml.xml
-----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.oa.domain">
<class name="User" table="itcast_user">
<id name="id" type="long">
<generator class="native"></generator>
</id>
<property name="loginName" column="loginName"></property>
<!-- 特殊属性和关联属性 -->
</class>
</hibernate-mapping>
-----------------------------------------------------------------------------------------
5.映射关系模版
-----------------------------------------------------------------------------------------
写完javabean后,写映射文件。
1,先写简单属性,有关联关系的属性,后面来写。
映射模板:
多对一:
<!-- ?属性: 表示我与?的多对一关系 -->
<many-to-one name="{1}" class="{2}" column="{1}Id"></many-to-one>
注; 先写多对一的column属性值,然后再将该值复制到对应的一对多的key。column属性即可
一对多:
<!-- ?属性: 表示我与?的一对多关系 -->
<set name="{1}">
<key column="先找到对应的多对一关系,然后在拷贝其column的值,与其相同"></key>
<one-to-many class="{2}"/>
</set>
注: 多对一和一对多,先写多对一,再写一对多。因为一对多的外键要与对应多对一的外键相同。
一对一:
<!-- ?属性,表示我与?的一对一关系
采用基于外键的一对一映射。本方有外键。
-->
<many-to-one name="{1}" class="{2}" column="{1}Id" unique="true"></many-to-one>
多对多:
<!-- ?属性: 表示我与?的多对多关系 -->
<set name="{1}" table="">
<key column="当前类的名称(首字母小写)加Id后缀"></key>
<many-to-many class="{2}" column="对方类的名称(首字母小写)加Id后缀"></many-to-many>
</set>
注: table中间表的名称要俩者一样,一般为俩个类名小写中间用_连接
-----------------------------------------------------------------------------------------
6.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 0. 引入类扫描的注解解析器 -->
<context:component-scan base-package="cn.itcast.oa"></context:component-scan>
<!-- 1.1 引入外部的数据库连接信息配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 1.2 配置C3P0数据源(数据库连接池)信息 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据库连接信息 注意:第三个为user字段,而非username字段 -->
<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的官方文档中获取 -->
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--连接池中保留的最小连接数。Default: 3 -->
<property name="minPoolSize" value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="5"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="3"></property>
<!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
<property name="maxStatements" value="8"></property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection" value="5"></property>
<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="1800"></property>
</bean>
<!-- 1.3 spring整合hibernate配置sessionFactory的方式 默认单例模式-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 1.4 配置声明式的事务管理(采用基于注解的形式) -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
-----------------------------------------------------------------------------------------
7.jdbc.properties
-----------------------------------------------------------------------------------------
jdbcUrl =jdbc:mysql://localhost:3306/itcastoa
driverClass =com.mysql.jdbc.Driver
username =用户名
password =密码
-----------------------------------------------------------------------------------------
三、测试类
1. TestSpring.java
-----------------------------------------------------------------------------------------
public class TestSpring {
private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 测试sessionFactory
@Test
public void testSesstionFactory(){
SessionFactory sc = (SessionFactory) ac.getBean("sessionFactory");
System.out.println(sc.openSession());
}
// 测试事务管理
@Test
public void testTx(){
TestService service = (TestService) ac.getBean("testService");
service.saveTwoUsers();
}
// 测试testAction
@Test
public void testAction(){
TestAction testAction = (TestAction) ac.getBean("testAction");
System.out.println(testAction);
}
}
-----------------------------------------------------------------------------------------
2.TestService.java
-----------------------------------------------------------------------------------------
// 相当于在spring配置中声明id为testService的bean
@Service
public class TestService {
// 使用spring配置中的sessionFactory
@Resource
private SessionFactory sessionFactory;
// 开启事务
@Transactional
public void saveTwoUsers(){
Session session = sessionFactory.getCurrentSession();
// 注:自己定义User类和表(只有id属性只用来测试即可,配置User.hbm.xml,并添加)
session.save(new User());
// int i = 1/0;
session.save(new User());
}
}
-----------------------------------------------------------------------------------------
3.TestAction.java
-----------------------------------------------------------------------------------------
@Controller
public class TestAction extends ActionSupport {
@Resource
private TestService testService;
public String execute() throws Exception {
// 注: syst为输出当前调用的方法的名称
System.out.println("TestAction.execute()");
System.out.println("TestAction.execute()" + testService);
testService.saveTwoUsers();
return SUCCESS;
}
}
-----------------------------------------------------------------------------------------