【SSH项目实战】国税协同平台-2.环境搭建和整合

框架整合

2.1新建数据库及web项目
2.1.1创建itcastTax数据库
-- 创建数据库
[sql]  view plain copy
  1. 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中添加几个常用属性:
[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5.   
  6.   
  7. <struts>  
  8.   
  9.   
  10.     <!-- 禁用动态方法访问 -->  
  11.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
  12.     <!-- 配置成开发模式 -->  
  13.     <constant name="struts.devMode" value="true" />  
  14.     <!-- 配置拓展名为action -->  
  15.     <constant name="struts.action.extention" value="action" />  
  16.     <!-- 把主题配置成simple -->  
  17.     <constant name="struts.ui.theme" value="simple" />  
  18.       
  19. </struts>  

配置web.xml:添加struts2 过滤器:

[html]  view plain copy
  1. <filter>  
  2.      <filter-name>struts2</filter-name>     
  3.      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  4. </filter>  
  5.   
  6. <filter-mapping>  
  7.      <filter-name>struts2</filter-name>  
  8.      <url-pattern>*.action</url-pattern>  
  9. </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目录下;

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  7.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  8.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  9.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  10.       
  11. </beans>  

在web.xml中注册spring监听器,启动spring容器:
[html]  view plain copy
  1. <!-- spring监听器 -->  
  2. <listener>  
  3.        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  4. </listener>  
  5. <context-param>  
  6.         <param-name>contextConfigLocation</param-name>  
  7.         <param-value>classpath:applicationContext.xml</param-value>  
  8. </context-param>  

三大框架的环境已经添加完毕,下面我们开始整合。

2.3整合测试项目
2.3.1整合struts 和 spring
预期:如果可以在action中能够正确调用service里面的方法执行并返回到一个页面中;那么我们认定struts和spring的整合是成功的。

编写 TestService 接口 和实现类 TestServiceImpl
[java]  view plain copy
  1. package cn.edu.hpu.tax.service;  
  2.   
  3.   
  4. public interface TestService {  
  5.     //输出  
  6.     public void say();  
  7. }  


[java]  view plain copy
  1. package cn.edu.hpu.tax.service.impl;  
  2.   
  3. import org.springframework.stereotype.Service;  
  4.   
  5. import cn.edu.hpu.tax.service.TestService;  
  6.   
  7. @Service("testService")  
  8. public class TestServiceImpl implements TestService{  
  9.   
  10.   
  11.     @Override  
  12.     public void say() {  
  13.         System.out.println("Hello Service!");  
  14.     }  
  15.       
  16. }  

编写JUnit测试类,测试spring加载是否正确:
[java]  view plain copy
  1. package cn.edu.hpu.tax.test;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import cn.edu.hpu.tax.service.TestService;  
  7.   
  8.   
  9. public class TestMerge {  
  10.   
  11.   
  12.     private ClassPathXmlApplicationContext ctx;  
  13.     @Test  
  14.     public void testSpring(){  
  15.         ctx=new ClassPathXmlApplicationContext("applicationContext.xml");  
  16.         TestService ts=(TestService)ctx.getBean("testService");  
  17.         ts.say();  
  18.     }  
  19. }  

在applicationContext.xml中添加bean扫描配置信息;
这边使用导入配置文件的方式配置。
①首先在cn.edu.hpu.test.conf中建立test-spring.xml,里面内容:
[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  7.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  8.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  9.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  10.       
  11.     <!-- 扫描Service -->  
  12.     <context:component-scan base-package="cn.edu.hpu.tax.test.service.impl"></context:component-scan>  
  13. </beans>  

里面的配置就是普通的bean扫描,只是将扫描范围缩小了。

②将test-spring.xml导入到applicationContext.xml中如下:
[html]  view plain copy
  1. <!-- 引入外部spring配置文件 -->  
  2. <import resource="classpath:cn/edu/hpu/tax/*/conf/*-spring.xml"/>  

运行TestMerge的testSpring方法,运行成功,说明我们的spring配置没有问题。

下面测试我们的struts和spring是否能整合使用:
编写TestAction类:
[java]  view plain copy
  1. package cn.edu.hpu.tax.test;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import cn.edu.hpu.tax.service.TestService;  
  6.   
  7. import com.opensymphony.xwork2.ActionSupport;  
  8.   
  9. public class TestAction extends ActionSupport{  
  10.       
  11.     @Resource  
  12.     TestService testService;  
  13.   
  14.   
  15.     //默认方法  
  16.     public String execute(){  
  17.         testService.say();  
  18.         return SUCCESS;  
  19.     }  
  20. }  

注意:
注入testService;有两种方式:
(1)注解注入
[java]  view plain copy
  1. @Resource  
  2. TestService testService;  
这种方式spring会按照"testService"找相应的类去注入

[java]  view plain copy
  1. @Resource  
  2. public void setTestService(TestService testService) {  
  3.     this.testService = testService;  
  4. }  
这种方式spring会按照setTestService中的"testService"(找的时候首字母转为小写)找相应的类去注入。使用set方法是为了在注入前加入一些其他代码(在set方法里)。

(2)配置文件注入
也是在action加入set方法,不过不用加注解,然后在struts配置文件的property中加入想注入的service类就可以了。

在test的conf文件夹下新建test-struts.xml中配置TestAction :
[html]  view plain copy
  1. <struts>  
  2.     <package name="test-action" namespace="/" extends="struts-default">  
  3.         <action name="test_*" class="cn.edu.hpu.tax.test.TestAction" method="{1}">  
  4.             <result name="success">/WEB-INF/jsp/test/test.jsp</result>  
  5.         </action>  
  6.     </package>  
  7. </struts>  

将test-struts.xml导入到struts.xml文件中。
[html]  view plain copy
  1. <!-- 包含test的struts配置文件 -->  
  2. <include file="cn/edu/hpu/test/tax/conf/test-struts.xml"/>  

在webRoot/WEB-INF/jsp目录下新建test/test.jsp:
[html]  view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4.   <head>  
  5.     <title>My JSP</title>  
  6.   <body>  
  7.     测试struts与spring整合成功!  
  8.   </body>  
  9. </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数据库连接源:
[html]  view plain copy
  1. <pre name="code" class="html"><!-- 导入外部的properties配置文件 -->  
  2. <context:property-placeholder location="classpath:db.properties" />  
  3.   
  4. <!-- 配置c3p0数据源 -->  
  5. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
  6.     <property name="jdbcUrl" value="${jdbcUrl}"></property>  
  7.     <property name="driverClass" value="${driverClass}"></property>  
  8.     <property name="user" value="${user}"></property>  
  9.     <property name="password" value="${password}"></property>  
  10.     <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->  
  11.     <property name="initialPoolSize" value="${initialPoolSize}"></property>  
  12.     <!--连接池中保留的最小连接数。Default: 3 -->  
  13.     <property name="minPoolSize" value="3"></property>  
  14.     <!--连接池中保留的最大连接数。Default: 15 -->  
  15.     <property name="maxPoolSize" value="${maxPoolSize}"></property>  
  16.     <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->  
  17.     <property name="acquireIncrement" value="3"></property>  
  18.     <!--最大空闲时间,1800秒内未使用则连接被丢弃,若为0则永不丢弃。Default: 0 -->  
  19.     <property name="maxIdleTime" value="1800"></property>  
  20. </bean>  
 
2、db.properties 
[plain]  view plain copy
  1. jdbcUrl=jdbc:mysql://localhost:3306/hputax?  
  2. useUnicode=true&characterEncoding=utf8  
  3. driverClass=com.mysql.jdbc.Driver  
  4. user=root  
  5. password=1234  
  6. initialPoolSize=10  
  7. maxPoolSize=30  

3、配置sessionFactory,并将dataSource指向c3p0创建的dataSource:
[html]  view plain copy
  1. <bean id="sessionFactory"  
  2.     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  3.     <property name="dataSource" ref="dataSource"></property>  
  4.     <property name="hibernateProperties">  
  5.         <props>  
  6.             <!-- 数据库方言 -->  
  7.             <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>  
  8.             <prop key="hibernate.show_sql">true</prop>  
  9.             <!-- 通过hbm配置文件去更新 -->  
  10.             <prop key="hibernate.hbm2ddl.auto">update</prop>  
  11.             <prop key="javax.persistence.validation.mode">none</prop>  
  12.         </props>  
  13.     </property>  
  14.     <property name="mappingLocations">  
  15.         <list>  
  16.             <value>classpath:cn/edu/hpu/tax/test/entity/*.hbm.xml</value>  
  17.         </list>  
  18.     </property>  
  19. </bean>  

编写实体类Person
[java]  view plain copy
  1. package cn.edu.hpu.tax.test.entity;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Person implements Serializable {  
  6.     private String id;  
  7.     private String name;  
  8.       
  9.     public Person() {  
  10.   
  11.   
  12.     }  
  13.       
  14.     public Person(String name) {  
  15.         this.name = name;  
  16.     }  
  17.   
  18.   
  19.     public String getId() {  
  20.         return id;  
  21.     }  
  22.     public void setId(String id) {  
  23.         this.id = id;  
  24.     }  
  25.     public String getName() {  
  26.         return name;  
  27.     }  
  28.     public void setName(String name) {  
  29.         this.name = name;  
  30.     }  
  31.       
  32.       
  33. }  

和对应的映射文件Person.hbm.xml:
[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4.   
  5.   
  6. <hibernate-mapping>  
  7.     <class name="cn.edu.hpu.tax.test.entity.Person" table="person">  
  8.         <id name="id" type="java.lang.String">  
  9.             <column name="id" length="32" />  
  10.             <generator class="uuid.hex" />  
  11.         </id>  
  12.         <property name="name" type="java.lang.String">  
  13.             <column name="name" length="20" not-null="true" />  
  14.         </property>  
  15.     </class>  
  16. </hibernate-mapping>  


我们运行testHibernate()测试方法:
[java]  view plain copy
  1. package cn.edu.hpu.tax.test;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.Transaction;  
  6. import org.junit.Test;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.   
  9.   
  10. import cn.edu.hpu.tax.service.TestService;  
  11. import cn.edu.hpu.tax.test.entity.Person;  
  12.   
  13.   
  14. import com.opensymphony.xwork2.interceptor.annotations.Before;  
  15.   
  16.   
  17. public class TestMerge {  
  18.   
  19.   
  20.     private ClassPathXmlApplicationContext ctx;  
  21.     @Before  
  22.     public void testCtx(){  
  23.         ctx=new ClassPathXmlApplicationContext("applicationContext.xml");  
  24.     }  
  25.       
  26.     @Test  
  27.     public void testSpring(){  
  28.         TestService ts=(TestService)ctx.getBean("testService");  
  29.         ts.say();  
  30.     }  
  31.       
  32.     @Test  
  33.     public void testHibernate(){  
  34.         SessionFactory sf=(SessionFactory)ctx.getBean("sessionFactory");  
  35.         Session session=sf.openSession();  
  36.         Transaction transaction=session.beginTransaction();  
  37.         //保存人员  
  38.         session.save(new Person("人员1"));  
  39.         transaction.commit();  
  40.         session.close();  
  41.     }  
  42. }  

看到我们的控制台输出一句插入语句,并且我们的数据库已经有值:



测试框架分层的整合(service 与 dao)
TestDao 中新增方法 save ,在TestService中通过调用testDao来保存人员信息。
[java]  view plain copy
  1. package cn.edu.hpu.tax.test.dao;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import cn.edu.hpu.tax.test.entity.Person;  
  6.   
  7. public interface TestDao {  
  8.       
  9.     //保存人员  
  10.     public void save(Person person);  
  11.       
  12.     //根据id查询人员  
  13.     public Person findPerson(Serializable id);  
  14. }  

[java]  view plain copy
  1. package cn.edu.hpu.tax.test.dao.impl;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  6.   
  7. import cn.edu.hpu.tax.test.dao.TestDao;  
  8. import cn.edu.hpu.tax.test.entity.Person;  
  9.   
  10.   
  11. public class TestDaoImpl extends HibernateDaoSupport implements TestDao{  
  12.   
  13.   
  14.     @Override  
  15.     public void save(Person person) {  
  16.         getHibernateTemplate().save(person);  
  17.     }  
  18.       
  19.     @Override  
  20.     public Person findPerson(Serializable id) {  
  21.         return getHibernateTemplate().get(Person.class, id);  
  22.     }     
  23.   
  24.   
  25. }  
因为上面使用了HibernateDaoSupport,所以我们要在test-spring注入sessionFactory(在HibernateDaoSupport中已经封装好了setSessionFactory()方法,所以开发人员不用操心)
[html]  view plain copy
  1. <bean id="testDao" class="cn.edu.hpu.tax.test.dao.impl.TestDaoImpl">  
  2.      <property name="sessionFactory" ref="sessionFactory"></property>  
  3. </bean>  

然后我们的Service层去调用Dao的方法:
[java]  view plain copy
  1. package cn.edu.hpu.tax.test.service.impl;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.springframework.stereotype.Service;  
  8.   
  9. import cn.edu.hpu.tax.test.dao.TestDao;  
  10. import cn.edu.hpu.tax.test.entity.Person;  
  11. import cn.edu.hpu.tax.test.service.TestService;  
  12.   
  13.   
  14. @Service("testService")  
  15. public class TestServiceImpl implements TestService{  
  16.   
  17.   
  18.     @Resource  
  19.     TestDao testDao;  
  20.       
  21.     @Override  
  22.     public void say() {  
  23.         System.out.println("Hello Service!");  
  24.     }  
  25.   
  26.   
  27.     @Override  
  28.     public Person findPerson(Serializable id) {  
  29.         return testDao.findPerson(id);  
  30.     }  
  31.   
  32.   
  33.     @Override  
  34.     public void save(Person person) {  
  35.         testDao.save(person);  
  36.     }  
  37.       
  38. }  

下面我们编写一个测试方法:
[java]  view plain copy
  1. @Test  
  2. public void testServiceAndDao(){  
  3.     TestService ts=(TestService)ctx.getBean("testService");  
  4.     ts.save(new Person("tom"));  
  5. }  

运行测试方法,发现成功在数据库中添加person信息:



然后我们来测试查找,将刚刚存储的数据查出来:
[java]  view plain copy
  1. @Test  
  2. public void testServiceAndDao2(){  
  3.     TestService ts=(TestService)ctx.getBean("testService");  
  4.     System.out.println(ts.findPerson("402881e6507a17b501507a17b69f0000").getName());  
  5. }  

发现取值成功:


2.3.3配置spring事务管理
[html]  view plain copy
  1. <!-- 事务管理 -->   
  2. <bean id="txManager"  
  3.     class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  4.     <property name="sessionFactory" ref="sessionFactory" />  
  5. </bean>  
  6.   
  7.   
  8. <!-- 事务通知 -->  
  9. <tx:advice id="txAdvice" transaction-manager="txManager">  
  10.     <tx:attributes>  
  11.         <tx:method name="find*" read-only="true" />  
  12.         <tx:method name="get*" read-only="true" />  
  13.         <tx:method name="load*" read-only="true" />  
  14.         <tx:method name="list*" read-only="true" />  
  15.         <tx:method name="search*" read-only="true" />  
  16.         <tx:method name="*" rollback-for="Throwable" />  
  17.     </tx:attributes>  
  18. </tx:advice>  
  19.   
  20.   
  21. <!-- 配置需要进行事务控制的类 -->  
  22. <aop:config>  
  23.     <aop:pointcut id="serviceOperation" expression="bean(*Service)" />  
  24.     <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
  25. </aop:config>  

【注意:上面的pointcut  expression 表示拦截以Service结尾的bean,或者可写成
execution(* cn.itcast..service.impl.*.*(..))】
完善 TestService接口和TestServiceImpl;利用service中的操作来验证上面配置的事务管理是否生效。

测试方法
我们在Service中在find方法前进行save:
[java]  view plain copy
  1. @Override  
  2. public Person findPerson(Serializable id) {  
  3.     save(new Person("jack"));  
  4.     return testDao.findPerson(id);  
  5. }  

然后我们测试:
[java]  view plain copy
  1. @Test  
  2. public void testTransationReadOnly(){  
  3.     //只读事务,如果在只读事务中出现更新操作则回滚  
  4.     TestService ts=(TestService)ctx.getBean("testService");  
  5.     System.out.println(ts.findPerson("402881e6507a17b501507a17b69f0000").getName());  
  6. }  

运行之后我们发现报了这个错误:


说明我们的只读控制是成功的。

接下来测试我们的回滚:
我们在Service的save插入值语句之后,故意写一条错误的代码:
[java]  view plain copy
  1. @Override  
  2. public void save(Person person) {  
  3.     testDao.save(person);  
  4.     int i=1/0;  
  5. }  

测试方法:
[java]  view plain copy
  1. @Test  
  2. public void testTransationRoolBack(){  
  3.     //回滚事务,如果在只读事务中出现任务异常则回滚先前的操作  
  4.     TestService ts=(TestService)ctx.getBean("testService");  
  5.     ts.save(new Person("tom2"));  
  6. }  

执行测试方法,发现报错:

然后数据库并没有存储名字为“tom2”的数据,说明我们的事务回滚控制成功!

至此,我们的框架配置、整合和测试完毕

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值