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

框架整合

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

时间: 2024-09-06 11:21:46

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

【SSH项目实战】国税协同平台-1.项目介绍

项目介绍 1.1项目背景 国税协同办公平台包括了行政管理.后勤服务.在线学习.纳税服务.我的空间等几个子系统:我们本次主要的开发功能是纳税服务子系统的部分模块和基于纳税服务子系统信息的个人工作台首页.纳税服务子系统是办税PC前端或移动端的后台管理系统,主要包括的功能有系统角色管理.用户管理.信息发布管理.投诉受理.纳税咨询.易告知.服务预约.服务调查等模块. 系统的主界面: 我们要做的模块界面: 1.2项目前期 项目前期:一般是由客户经理从客户那边了解到有关该项目的招标信息,然后开发公司再组织竞

【SSH项目实战】国税协同平台-14.系统、子系统首页&amp;amp;登录功能1

我们做完了用户与角色的分配,在设置用户在相应的角色下的操作之前,我们先完成用户的登录功能. 首先,我们先加载我们的系统的首页和子首页.很简单,就是转发到一个jsp页面而已,我们先写一个HomeAction来设置跳转功能: package cn.edu.hpu.tax.core.action; import com.opensymphony.xwork2.ActionSupport; public class HomeAction extends ActionSupport{ //跳转到首页 pu

Microsoft NLayerApp案例理论与实践 - 项目简“.NET研究”介与环境搭建

项目简介 Microsoft – Spain团队有一个很不错的面向领域多层分布式项目案例:Microsoft – Domain Oriented N-Layered .NET 4.0 App Sample(在本系列文章中,我使用NLayerApp作为该项目的名称进行介绍),在codeplex上的地址是:http://microsoftnlayerapp.codeplex.com/. 它是学习领域驱动设计(DDD)的一个非常不错的案例项目.该项目采用的是经典的DDD架构,而不是CQRS架构,但我觉

Hibernate环境搭建+struts整合

说明:本文档,是和struts2+hibernate的整合示例. lib下还有struts2的jar包,本示例没有显示.struts2的搭建参考struts2的环境搭建 一下载hibernate的jar包,并将相关jar包导入的项目web-inf的lib下 少了一个jar包,报错 二:配置hibernate.cfg.xml文档 1 <!DOCTYPE hibernate-configuration PUBLIC 2 "-//Hibernate/Hibernate Configuration

【SSH项目实战】国税协同平台-3.资源文件分类&amp;amp;log4j&amp;amp;抽取BaseAction

上次我们搭建了SSH框架的环境,然后做了单元测试,下面我们继续来完善我们工厂的准备工作. 3.1资源文件分类 (1)将配置文件归类到新建config文件夹: (2)源代码目录按照功能模块进行划分:cn.edu.hpu.子系统.功能模块.* (3)Jsp放置到WEB-INF目录下: (4)其它: 新建一个test源文件架(Source Folder),我们把上次所有测试的代码全部移入test文件夹下,然后专门为配置文件创建一个conf源文件夹,将配置文件移入,然后src中先建立一个包准备放新写的代

【SSH项目实战】国税协同平台-31.我要投诉功能1

我们之前完成了投诉回复和保存功能,这次我们将要完成历史受理信息的显示 以及数据回显功能,当然还有用户编写投诉信息的入口,我们这次继续. 可以注意到,在deilUI.jsp上我们之前的投诉人信息显示,不管是匿名还是不匿名,投诉人的姓名.手机号码都是显示出来的: <tr> <td class="tdBg">投诉人姓名:</td> <td><s:property value="complain.compName"/&g

【SSH项目实战】国税协同平台-4.用户管理需求分析&amp;amp;CRUD方法1

上次我们完成了日志模块的配置和基础增删改查类,下面我们根据用户的需求来正式开发项目的业务模块. 下面我们主要来开发系统用户管理的模块 我们有用户的功能说明书,打开功能说明书来看看这个模块需要什么功能: 功能说明 用户管理:可以根据用户名查询系统用户:在页面中点击"新增"可以添加用户.点击删除可以批量删除选中的用户."导出"则导出所有的用户列表到excel文件中并弹出下载提示框给用户下载:"导入"将需要用户将本地的用户列表按照一定格式将excel中

【SSH项目实战】国税协同平台-33.quartz&amp;amp;SimpleTrigge

在我们"投诉管理"和"我要投诉"这两个模块完成之后,我们要做一个"自动投诉受理"功能. 我们来回顾一下"自动投诉受理"功能的需求分析: 自动投诉受理:在每个月月底最后一天对本月之前的投诉进行自动处理:将投诉信息的状态改为已失效.在后台管理中不能对该类型投诉进行回复. 自动投诉受理是在一定时间内自动的调度任务执行投诉状态的更新:那么需要使用任务调度,常见的任务调度有Jdk 的Timer 以及 quartz任务调度框架等.在spr

【SSH项目实战】国税协同平台-7.POI导入用户列表文件

上次我们使用POI技术完成了用户列表的打印工作,下面我们来完成用户列表Excel文件的导入. 我们要导入这个Excel文件到我们的系统中: 确切的说,是我们要将excel中的数据导入到数据库中保存起来 我们的操作过程: 1.获取excel文件 2.导入 2.1.读取工作簿 2.2.读取工作表 2.3.读取行 2.4.读取单元格 2.5.保存用户 下面我们来进行具体的实现工作 我们在用户列表的jsp页面中可以看到还有一个"导出"的按钮, <input type="butt