框架整合
2.1新建数据库及web项目
2.1.1创建itcastTax数据库
-- 创建数据库
CREATE DATABASE itcastTax DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
我们使用的是Mysql数据库
2.1.2新建web项目
新建工作空间指定项目编码(或工作空间编码)为utf-8,再建 web project,配置buildpath
添加jstl的jar包和mysql驱动包;
javax.servlet.jsp.jstl.jar
jstl-impl.jar
mysql-connector-java-5.1.32-bin.jar
2.2框架整合
2.2.1添加struts2的jar包和配置文件
添加jar包:
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-lang-2.4.jar
commons-lang3-3.2.jar
freemarker-2.3.19.jar
ognl-3.0.6.jar
struts2-core-2.x.jar
struts2-spring-plugin-2.x.jar
xwork-core-2.x.jar
到web-inf/lib目录下。
添加struts.xml到src目录下。
在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.enable.DynamicMethodInvocation" value="false" /> <!-- 配置成开发模式 --> <constant name="struts.devMode" value="true" /> <!-- 配置拓展名为action --> <constant name="struts.action.extention" value="action" /> <!-- 把主题配置成simple --> <constant name="struts.ui.theme" value="simple" /> </struts>
配置web.xml:添加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>*.action</url-pattern> </filter-mapping>
2.2.2添加hibernate的jar包和配置文件添加hibernate jar包:
到web-inf/lib目录下。至于hibernate.cfg.xml文件,因项目使用spring来整合管理实体和数据库的连接等hibernate原本的工作,所以这个配置文件不再需要。
2.2.3添加spring的jar包和配置文件添加spring3.0.2中的jar包:
添加spring配置文件applicationContext.xml 到src目录下;
<?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:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> </beans>
在web.xml中注册spring监听器,启动spring容器:
<!-- spring监听器 --> <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>
三大框架的环境已经添加完毕,下面我们开始整合。
2.3整合测试项目
2.3.1整合struts 和 spring
预期:如果可以在action中能够正确调用service里面的方法执行并返回到一个页面中;那么我们认定struts和spring的整合是成功的。
编写 TestService 接口 和实现类 TestServiceImpl
package cn.edu.hpu.tax.service; public interface TestService { //输出 public void say(); }
package cn.edu.hpu.tax.service.impl; import org.springframework.stereotype.Service; import cn.edu.hpu.tax.service.TestService; @Service("testService") public class TestServiceImpl implements TestService{ @Override public void say() { System.out.println("Hello Service!"); } }
编写JUnit测试类,测试spring加载是否正确:
package cn.edu.hpu.tax.test; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.edu.hpu.tax.service.TestService; public class TestMerge { private ClassPathXmlApplicationContext ctx; @Test public void testSpring(){ ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); TestService ts=(TestService)ctx.getBean("testService"); ts.say(); } }
在applicationContext.xml中添加bean扫描配置信息;
这边使用导入配置文件的方式配置。
①首先在cn.edu.hpu.test.conf中建立test-spring.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:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 扫描Service --> <context:component-scan base-package="cn.edu.hpu.tax.test.service.impl"></context:component-scan> </beans>
里面的配置就是普通的bean扫描,只是将扫描范围缩小了。
②将test-spring.xml导入到applicationContext.xml中如下:
<!-- 引入外部spring配置文件 --> <import resource="classpath:cn/edu/hpu/tax/*/conf/*-spring.xml"/>
运行TestMerge的testSpring方法,运行成功,说明我们的spring配置没有问题。
下面测试我们的struts和spring是否能整合使用:
编写TestAction类:
package cn.edu.hpu.tax.test; import javax.annotation.Resource; import cn.edu.hpu.tax.service.TestService; import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport{ @Resource TestService testService; //默认方法 public String execute(){ testService.say(); return SUCCESS; } }
注意:
注入testService;有两种方式:
(1)注解注入
@Resource TestService testService;
这种方式spring会按照"testService"找相应的类去注入
@Resource public void setTestService(TestService testService) { this.testService = testService; }
这种方式spring会按照setTestService中的"testService"(找的时候首字母转为小写)找相应的类去注入。使用set方法是为了在注入前加入一些其他代码(在set方法里)。
(2)配置文件注入
也是在action加入set方法,不过不用加注解,然后在struts配置文件的property中加入想注入的service类就可以了。
在test的conf文件夹下新建test-struts.xml中配置TestAction :
<struts> <package name="test-action" namespace="/" extends="struts-default"> <action name="test_*" class="cn.edu.hpu.tax.test.TestAction" method="{1}"> <result name="success">/WEB-INF/jsp/test/test.jsp</result> </action> </package> </struts>
将test-struts.xml导入到struts.xml文件中。
<!-- 包含test的struts配置文件 --> <include file="cn/edu/hpu/test/tax/conf/test-struts.xml"/>
在webRoot/WEB-INF/jsp目录下新建test/test.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP</title> <body> 测试struts与spring整合成功! </body> </html>
在浏览器中输入:http://localhost/HpuTax/test.action(我的tomcat是80端口)查看后台是否能输入service中的打印信息:
测试成功!
2.3.2整合hibernate 和 spring
在applicationContext.xml中配置如下原本在hibernate.cfg.xml中需要配置的信息,在spring中配置后hibernate.cfg.xml 可删除(没有加就忽略)。
1、配置c3p0数据库连接源:
<pre name="code" class="html"><!-- 导入外部的properties配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize" value="${initialPoolSize}"></property> <!--连接池中保留的最小连接数。Default: 3 --> <property name="minPoolSize" value="3"></property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize" value="${maxPoolSize}"></property> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement" value="3"></property> <!--最大空闲时间,1800秒内未使用则连接被丢弃,若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime" value="1800"></property> </bean>
2、db.properties
jdbcUrl=jdbc:mysql://localhost:3306/hputax? useUnicode=true&characterEncoding=utf8 driverClass=com.mysql.jdbc.Driver user=root password=1234 initialPoolSize=10 maxPoolSize=30
3、配置sessionFactory,并将dataSource指向c3p0创建的dataSource:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <!-- 数据库方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <!-- 通过hbm配置文件去更新 --> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <property name="mappingLocations"> <list> <value>classpath:cn/edu/hpu/tax/test/entity/*.hbm.xml</value> </list> </property> </bean>
编写实体类Person
package cn.edu.hpu.tax.test.entity; import java.io.Serializable; public class Person implements Serializable { private String id; private String name; public Person() { } public Person(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
和对应的映射文件Person.hbm.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> <class name="cn.edu.hpu.tax.test.entity.Person" table="person"> <id name="id" type="java.lang.String"> <column name="id" length="32" /> <generator class="uuid.hex" /> </id> <property name="name" type="java.lang.String"> <column name="name" length="20" not-null="true" /> </property> </class> </hibernate-mapping>
我们运行testHibernate()测试方法:
package cn.edu.hpu.tax.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.edu.hpu.tax.service.TestService; import cn.edu.hpu.tax.test.entity.Person; import com.opensymphony.xwork2.interceptor.annotations.Before; public class TestMerge { private ClassPathXmlApplicationContext ctx; @Before public void testCtx(){ ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); } @Test public void testSpring(){ TestService ts=(TestService)ctx.getBean("testService"); ts.say(); } @Test public void testHibernate(){ SessionFactory sf=(SessionFactory)ctx.getBean("sessionFactory"); Session session=sf.openSession(); Transaction transaction=session.beginTransaction(); //保存人员 session.save(new Person("人员1")); transaction.commit(); session.close(); } }
看到我们的控制台输出一句插入语句,并且我们的数据库已经有值:
测试框架分层的整合(service 与 dao)
TestDao 中新增方法 save ,在TestService中通过调用testDao来保存人员信息。
package cn.edu.hpu.tax.test.dao; import java.io.Serializable; import cn.edu.hpu.tax.test.entity.Person; public interface TestDao { //保存人员 public void save(Person person); //根据id查询人员 public Person findPerson(Serializable id); }
package cn.edu.hpu.tax.test.dao.impl; import java.io.Serializable; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import cn.edu.hpu.tax.test.dao.TestDao; import cn.edu.hpu.tax.test.entity.Person; public class TestDaoImpl extends HibernateDaoSupport implements TestDao{ @Override public void save(Person person) { getHibernateTemplate().save(person); } @Override public Person findPerson(Serializable id) { return getHibernateTemplate().get(Person.class, id); } }
因为上面使用了HibernateDaoSupport,所以我们要在test-spring注入sessionFactory(在HibernateDaoSupport中已经封装好了setSessionFactory()方法,所以开发人员不用操心)
<bean id="testDao" class="cn.edu.hpu.tax.test.dao.impl.TestDaoImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>
然后我们的Service层去调用Dao的方法:
package cn.edu.hpu.tax.test.service.impl; import java.io.Serializable; import javax.annotation.Resource; import org.springframework.stereotype.Service; import cn.edu.hpu.tax.test.dao.TestDao; import cn.edu.hpu.tax.test.entity.Person; import cn.edu.hpu.tax.test.service.TestService; @Service("testService") public class TestServiceImpl implements TestService{ @Resource TestDao testDao; @Override public void say() { System.out.println("Hello Service!"); } @Override public Person findPerson(Serializable id) { return testDao.findPerson(id); } @Override public void save(Person person) { testDao.save(person); } }
下面我们编写一个测试方法:
@Test public void testServiceAndDao(){ TestService ts=(TestService)ctx.getBean("testService"); ts.save(new Person("tom")); }
运行测试方法,发现成功在数据库中添加person信息:
然后我们来测试查找,将刚刚存储的数据查出来:
@Test public void testServiceAndDao2(){ TestService ts=(TestService)ctx.getBean("testService"); System.out.println(ts.findPerson("402881e6507a17b501507a17b69f0000").getName()); }
发现取值成功:
2.3.3配置spring事务管理
<!-- 事务管理 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 事务通知 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="find*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="load*" read-only="true" /> <tx:method name="list*" read-only="true" /> <tx:method name="search*" read-only="true" /> <tx:method name="*" rollback-for="Throwable" /> </tx:attributes> </tx:advice> <!-- 配置需要进行事务控制的类 --> <aop:config> <aop:pointcut id="serviceOperation" expression="bean(*Service)" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" /> </aop:config>
【注意:上面的pointcut expression 表示拦截以Service结尾的bean,或者可写成
execution(* cn.itcast..service.impl.*.*(..))】
完善 TestService接口和TestServiceImpl;利用service中的操作来验证上面配置的事务管理是否生效。
测试方法
我们在Service中在find方法前进行save:
@Override public Person findPerson(Serializable id) { save(new Person("jack")); return testDao.findPerson(id); }
然后我们测试:
@Test public void testTransationReadOnly(){ //只读事务,如果在只读事务中出现更新操作则回滚 TestService ts=(TestService)ctx.getBean("testService"); System.out.println(ts.findPerson("402881e6507a17b501507a17b69f0000").getName()); }
运行之后我们发现报了这个错误:
说明我们的只读控制是成功的。
接下来测试我们的回滚:
我们在Service的save插入值语句之后,故意写一条错误的代码:
@Override public void save(Person person) { testDao.save(person); int i=1/0; }
测试方法:
@Test public void testTransationRoolBack(){ //回滚事务,如果在只读事务中出现任务异常则回滚先前的操作 TestService ts=(TestService)ctx.getBean("testService"); ts.save(new Person("tom2")); }
执行测试方法,发现报错:
然后数据库并没有存储名字为“tom2”的数据,说明我们的事务回滚控制成功!
至此,我们的框架配置、整合和测试完毕
转载请注明出处:http://blog.csdn.net/acmman/article/details/49247179