您的位置:首页 > 其它

SSH框架整合开发详解(个人笔记)

2016-01-07 15:36 531 查看
一.创建数据库并设置编码。

A) create database oa default character set utf8。

二.MyEclipse工程

A) 在Myeclipse里创建web工程,并设置编码为utf8.

B) 添加框架环境

1.添加Junit4 library(Myeclipse自带)

2.添加Struts2环境

①所需Jar包

②配置文件:拷贝一个struts.xml模版到src目录,进行适当修改,在web.xml里配上需要的代码。

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<!-- 配置为开发模式 -->    <constant name="struts.devMode" value="true" />    <!-- 把扩展名配置为action -->    <constant name="struts.action.extension" value="action" />    <!-- 把主题配置为simple -->    <constant name="struts.ui.theme" value="simple" />	       <package name="default" namespace="/" extends="struts-default">      	<action name="" class="">      		<result name=""></result>      	</action>    </package>    <!-- Add packages here -->    </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>/*</url-pattern></filter-mapping>


3.添加Hibernate环境

①所需Jar包

②配置文件:拷贝一个hibernate.cfg.xml和映射文件*.hbm.xml模版到src目录,并进行适当修改。

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
	<!-- 1,数据库连接信息 -->	<property name="dialect">		org.hibernate.dialect.MySQL5InnoDBDialect	</property>	<property name="connection.url">jdbc:mysql:///oa</property>	<property name="connection.driver_class">com.jdbc.mysql.Driver</property>	<property name="connection.username">root</property>	<property name="connection.password">root</property>
	<!-- 2,其他配置 -->	<property name="show_sql">true</property>	<property name="hbm2ddl.auto">update</property>
	<!-- 3,导入映射文件 -->	<mapping resource="" />	</session-factory>
</hibernate-configuration>


User.hbm.xml

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.grace.oa.domain">
	<class name="User" table="grace_user">		<id name="id">            <generator class="native"/>		</id>		<property name="name" />	</class>	</hibernate-mapping>


4.添加Spring环境

①所需Jar包

②配置文件:拷贝一个appicationContext.xml/beans.xml模版到src目录

appicationContext.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:context="http://www.springframework.org/schema/context"	xmlns:tx="http://www.springframework.org/schema/tx"	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 		 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd			 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 自动扫描与装配bean,包括子包 -->	<context:component-scan base-package="cn.grace.oa"></context:component-scan>
	<!-- 导入外部的properties文件 -->	<context:property-placeholder location="classpath:jdbc.properties"/>
	<!-- 配置SessionFactory IOC-->	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">		<!-- 指定hibernate的配置文件位置 -->		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>		<!-- 配置c3p0数据库连接池 -->				<property name="dataSource">			<bean class="com.mchange.v2.c3p0.ComboPooledDataSource">				<!-- 数据连接信息 -->				<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="3"></property>				<!--连接池中保留的最小连接数。Default: 3 -->				<property name="minPoolSize" value="3"></property>				<!--连接池中保留的最大连接数。Default: 15 -->				<property name="maxPoolSize" value="5"></property>				<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->				<property name="acquireIncrement" value="3"></property>				<!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->				<property name="maxStatements" value="8"></property>				<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->				<property name="maxStatementsPerConnection" value="5"></property>				<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->				<property name="maxIdleTime" value="1800"></property>			</bean>		</property>	</bean>

	<!-- 配置声明式事务管理(采用注解的方式) AOP-->	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">		<property name="sessionFactory" ref="sessionFactory"></property>	</bean>	<!-- 注解驱动-->	<tx:annotation-driven transaction-manager="txManager"/> </beans>


5.整合Spring和Struts2 (IOC:让struts2的action交由容器管理)

在src目录下建Junit测试包进行测试

①单独测试struts2,新建TestAction类

a) TestAction.java

public class TestAction extends ActionSupport{		@Override	public String execute() throws Exception{		System.out.println("===>TestAction.execute()");		return "success";	}}


b)在struts.xml里配置相应action

<!-- 配置测试用的Action,未与Spring整合,class属性写类的全名 --><action name="test" class="cn.grace.oa.test.TestAction">	<result name="success">/test.jsp</result></action>


c)部署测试是否可以通过test.action正常访问test.jsp页面和是否输出"===>TestAction.execute()"

②单独测试Spring,新建SpringTest类(此时appicationContext.xml里面只需要一个装配和扫描bean的语句,否则可能报错

a) SpringTest.java

public class SpringTest {	private ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");		@Test	public void testBean() throws Exception{		TestAction testAction=(TestAction) ac.getBean("testAction");		System.out.println(testAction);	}}


b)此时Junit测试不能成功,必须在TestAction类上进行声明,并配置scope。

@Controller@Scope("prototype")public class TestAction extends ActionSupport{		@Override	public String execute() throws Exception{		System.out.println("==>TestAction.execute");		return "success";	}}


c)此时再进行Junit测试成功输出testAction.

d)声明一个bean(注解方式,有四种方式,根据不同类用相对应的方式)

效果跟在bean.xml里面写<bean id="" class=""></bean>功能是一样的

@Component("beanName")//不写beanName默认使用类名首字母小写,即testAction

@Controller

@Service

@Repository

配置bean的scope,默认为单例,修改为prototype

@Scope("prototype")

③测试Struts2和Spring整合

a)在web.xml中配置一个监听器

<!-- 配置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>


b) 加一个jar包:struts2-spring-plugin-2.1.8.1.jar

将struts.xml中的action的class从路径改为bean名称,再进行测试,看是否整合成功

<!-- 配置测试用的Action,未与Spring整合,class属性写类的全名 --><!-- 当Struts2与Spring整合后,class属性可以写bean的名称 --><action name="test" class="testAction">	<result name="success">/test.jsp</result></action>


c)部署测试是否可以通过test.action正常访问test.jsp页面,正常访问test.jsp代表整合成功。

6.整合Spring和Hibernate(1.管理SessionFactory实例(只需要一个)2.声明式事务管理)

①SessionFactory

a)在applicationContext.xml里配置sessionFactoryv(见上文appicationContext.xml),并在hibernate.cfg.xml去掉重复的连接数据库的信息

b)新建一个jdbc.properties用来存放dataSource用到的数据库连接信息,并在applicationContext.xml导入该文件

applicationContext.xml(上文appicationContext.xml已配置)

<!-- 导入外部的properties文件 --><context:property-placeholder location="classpath:jdbc.properties"/>


jdbc.properties

jdbcUrl		= jdbc:mysql:///oa?characterEncoding=utf8driverClass	= com.mysql.jdbc.Driveruser		= rootpassword	= root


c)在SpringTest类里写测试方法,进行Junit测试。

@Testpublic void testSessionFactory() throws Exception{	SessionFactory sessionFactory=(SessionFactory) ac.getBean("sessionFactory");	System.out.println(sessionFactory);}


②声明式事务管理

a)在applicationContext.xml里配置声明式事务管理(上文appicationContext.xml已配置)

<!-- 配置声明式事务管理(采用注解的方式) AOP--><bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">	<property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 注解驱动--><tx:annotation-driven transaction-manager="txManager"/>


b)测试声明式事务管理(测试回滚)

i.新建一个用于测试的实体类:User.java(只需定义id和name及其构造方法即可)

ii.根据User写对应的User.hbm.xml映射文件

iii.在hibernate.cfg.xml导入映射文件

<mapping resource="cn/grace/oa/domain/User.hbm.xml" />


iV.新建一个TestService类

@Service("testService")public class TestService {		@Resource	private SessionFactory sessionFactory;		@Transactional	public void saveTwoUsers(){		Session session=sessionFactory.getCurrentSession();		session.save(new User());		int a=1/0;//会抛异常,因为声明了事务,因此会回滚		session.save(new User());	}}


V.在SpringTest类里写测试方法,进行Junit测试。

@Testpublic void testTransaction() throws Exception{	TestService testService=(TestService)ac.getBean("testService");	testService.saveTwoUsers();}


Vi如果数据库中有新创建的表,并且没有插入数据,则去掉异常int a=1/0;再进行正常插入,如果此时id 从2开始,则 测试成功,因为id为1的user在之前一次测试中,抛异常被回滚。至此,三大框架整合完毕。

7.对三大框架整合进行完整测试。

①修改TestAction.java为如下代码

@Controller@Scope("prototype")public class TestAction extends ActionSupport{		@Resource	private TestService testService;	@Override	public String execute() throws Exception{		//System.out.println("test");		testService.saveTwoUsers();		return "success";	}}


②Spring管理对象(事务),action处理请求,hibernate处理对象的存储。

③如果此时通过test.action能正常显示test.jsp并且在数据库中的user表中增加了2条记录,则整合成功。(可以再加入异常进行反复测试,如果还出现回滚现象,则代表成功)

本篇转自:http://blog.csdn.net/v123411739/article/details/24098759
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: