CREATE DATABASE itcastTax DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;我们使用的是Mysql数据库
<?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>
<!-- 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>
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!"); } }
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(); } }
<?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>
<!-- 引入外部spring配置文件 --> <import resource="classpath:cn/edu/hpu/tax/*/conf/*-spring.xml"/>
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; } }
@Resource TestService testService;这种方式spring会按照"testService"找相应的类去注入
@Resource public void setTestService(TestService testService) { this.testService = testService; }这种方式spring会按照setTestService中的"testService"(找的时候首字母转为小写)找相应的类去注入。使用set方法是为了在注入前加入一些其他代码(在set方法里)。
<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配置文件 --> <include file="cn/edu/hpu/test/tax/conf/test-struts.xml"/>
<%@ 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>
<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
<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>
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; } }
<?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>
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(); } }
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>
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")); }
@Test public void testServiceAndDao2(){ TestService ts=(TestService)ctx.getBean("testService"); System.out.println(ts.findPerson("402881e6507a17b501507a17b69f0000").getName()); }
<!-- 事务管理 --> <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>
@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()); }
@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")); }
至此,我们的框架配置、整合和测试完毕
转载请注明出处:http://blog.csdn.net/acmman/article/details/49247179