**1.1 创建数据库**
CREATE DATABASE itcastTax DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
2.1 新建工作空间指定项目编码(或工作空间编码)为utf-8,再建 web project,
2.2 配置buildpath
2.3 引入tomcat 的包:
2.4 添加jstl jar包和mysql驱动包;
2.5 添加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-2.x\apps\struts2-blank\WEB-INF\classes”下复制。
在struts.xml中添加几个常用属性:
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.action.extention" value="action" />
<constant name="struts.ui.theme" value="simple" />
配置web.xml:添加struts2 过滤器:
<filter>
<filter-name>struts2filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
*.action
filter-mapping>
3.1 添加hibernate jar包:
hibernate3.jar,lib/required/*.jar,lib\jpa\hibernate-jpa-2.0-api-1.0.0.Final.jar,lib\bytecode\cglib\cglib-2.2.jar到web-inf/lib目录下。
4.1添加spring3.0.2中的jar包
添加spring配置文件applicationContext.xml 到src目录下;
<import resource="classpath:cn/itcast/*/conf/*-spring.xml"/>
在web.xml中注册spring监听器,启动spring容器:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
5.1 整合struts 和 spring
预期:如果可以在action中能够正确调用service里面的方法执行并返回到一个页面中;那么我们认定struts和spring的整合是成功的。
编写JUnit测试类,测试spring加载是否正确:
package cn.itcast.test;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.test.entity.Person;
import cn.itcast.test.service.TestService;
public class TestMerge {
ClassPathXmlApplicationContext ctx;
@Before
public void loadCtx() {
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();
}
@Test
public void testServiceAndDao() {
TestService ts = (TestService)ctx.getBean("testService");
ts.save(new Person("人员2"));
//System.out.println(ts.findPerson("4028eea54c8cdb1f014c8cdb20ab0000").getName());
}
@Test
public void testTransationReadOnly() {//只读事务,如果在只读事务中出现更新操作则回滚
TestService ts = (TestService)ctx.getBean("testService");
System.out.println(ts.findPerson("4028eea54c8cdb1f014c8cdb20ab0000").getName());
}
@Test
public void testTransationRollback() {//回滚事务,如果操作中出现有任务异常则回滚先前的操作
TestService ts = (TestService)ctx.getBean("testService");
ts.save(new Person("人员4"));
}
}
编写 TestService 接口
package cn.itcast.test.service;
import java.io.Serializable;
import cn.itcast.test.entity.Person;
public interface TestService {
//输出
public void say();
//保存人员
public void save(Person person);
//根据id查询人员
public Person findPerson(Serializable id);
}
实现类 TestServiceImpl
package cn.itcast.test.service.impl;
import java.io.Serializable;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.itcast.test.dao.TestDao;
import cn.itcast.test.entity.Person;
import cn.itcast.test.service.TestService;
@Service("testService")
public class TestServiceImpl implements TestService {
@Resource
TestDao testDao;
@Override
public void say() {
System.out.println("service saying hi.");
}
@Override
public void save(Person person) {
testDao.save(person);
int i = 1/0;
}
@Override
public Person findPerson(Serializable id) {
save(new Person("test"));
return testDao.findPerson(id);
}
}
在applicationContext.xml中添加bean扫描配置信息;这边使用导入配置文件的方式配置。①首先在cn.itcast.test.conf中建立test-spring.xml,里面内容:
<context:component-scan base-package="cn.itcast.test.service.impl">context:component-scan>
②将test-spring.xml导入到applicationContext.xml中如下:
<import resource="classpath:cn/itcast/*/conf/*-spring.xml" />
编写TestAction类
package cn.itcast.test.action;
import javax.annotation.Resource;
import cn.itcast.test.service.TestService;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
@Resource
TestService testService;
public String execute(){
testService.say();
return SUCCESS;
}
}
在test的conf文件夹下新建test-struts.xml中配置TestAction :
<struts>
<package name="test" namespace="/" extends="struts-default">
<action name="test_*" class="cn.itcast.test.action.TestAction" method="{1}">
<result name="success">/WEB-INF/jsp/test/test.jspresult>
action>
package>
struts>
将test-struts.xml导入到struts.xml文件中。
<include file="cn/itcast/test/conf/test-struts.xml"/>
在webRoot目录下新建test/test.jsp
在浏览器中输入:http://localhost:8080/itcastTax/test.action 查看后
台是否能输入service中的打印信息。
5.2 整合hibernate 和 spring
在applicationContext.xml中配置如下原本在hibernate.cfg.xml中需要配置的信息,在spring中配置后hibernate.cfg.xml 可删除。
1、 配置c3p0数据库连接源:
导入外部的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>
<property name="initialPoolSize" value="${initialPoolSize}">property>
<property name="minPoolSize" value="3">property>
<property name="maxPoolSize" value="${maxPoolSize}">property>
<property name="acquireIncrement" value="3">property>
<property name="maxIdleTime" value="1800">property>
bean>
db.properties数据库配置文件
jdbcUrl=jdbc:mysql://localhost:3306/itcastTax?useUnicode=true&characterEncoding=utf8
driverClass=com.mysql.jdbc.Driver
user=root
password=root
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.MySQL5Dialectprop>
<prop key="hibernate.show_sql">trueprop>
<prop key="hibernate.hbm2ddl.auto">updateprop>
<prop key="javax.persistence.validation.mode">noneprop>
props>
property>
<property name="mappingLocations">
<list>
<value>classpath:cn/itcast/nsfw/*/entity/*.hbm.xmlvalue>
<value>classpath:cn/itcast/test/entity/*.hbm.xmlvalue>
list>
property>
bean>
编写实体类Person和对应的映射文件Person.hbm.xml:
用JUnit测试hibernate和spring的整合,在测试用例中启动spring容器的时候将扫描Person类根据其创建数据库表,并在测试时将向表插入一条数据。
测试hibernate,添加一个人员
@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来保存人员信息。
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);
}
}
@Service("testService")
public class TestServiceImpl implements TestService {
@Resource
TestDao testDao;
@Override
public void say() {
System.out.println("service saying hi.");
}
@Override
public void save(Person person) {
testDao.save(person);
//int i = 1/0;
}
5.3 配置spring事务管理
-->
id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
-->
id="txAdvice" transaction-manager="txManager">
name="find*" read-only="true" />
name="get*" read-only="true" />
name="load*" read-only="true" />
name="list*" read-only="true" />
name="search*" read-only="true" />
name="*" rollback-for="Throwable" />
-->
id="serviceOperation" expression="bean(*Service)" />
ref="txAdvice" pointcut-ref="serviceOperation" />
【注意:上面的pointcut expression 表示拦截以Service结尾的bean,或者可写成
execution(* cn.itcast..service.impl..(..))】
完善 TestService接口和TestServiceImpl;利用service中的操作来验证上面配置的事务管理是否生效。
dao中
Service中
1、 将配置文件归类到新建config文件夹;
2、 源代码目录按照功能模块进行划分:cn.itcast.子系统.功能模块.*
3、 Jsp放置到WEB-INF目录下;
4、 其它:
在控制台会报出日志log4j没有配置好配置文件的信息。
Slf4j 接口jar(slf4j-log4j12-1.6.1.jar)
log4j的jar包(com.springsource.org.apache.log4j-1.2.15),配置log4j.properties文件。
测试: