声明:本文是参照某个培训机构视频教程,然后由我自己整理出来的文档,至于是哪个机构就不打广告了。仅供初学者参考,高手可以不看。
搭建说明:在Myeclipse环境下搭建SS2H框架搭建,包含JUNIT单元测试。在搭建环境前得先创建一个web project工程,本人的工程名称为SS2H,使用的是MYsql数据库。
1.首先引入JUNIT的jar包(Myeclipse自带):右键工程项目SS2H——>Build path——>add libraries——>JUNIT——>选择JUNIT4.
2.搭建Struts2环境(本文使用的是struts-2.1.8.1)
(1)拷贝struts-2.1.8.1\apps\struts2-blank-2.1.8.1.war\WEB-INF\lib里面的六个jar包:xwork-core--2.1.6.jar, struts2-core-2.1.8.1.jar, ognl-2.7.3.jar, freemarker-2.3.15.jar , commons-io-1.3.2.jar , commons-fileupload-1.2.1.jar.将他们放到工程项目SS2H的WebRoot——WEB-INF——lib文件夹里面。
(2)配置struts.xml以及web.xml文件:
复制struts-2.1.8.1\apps\struts2-blank-2.1.8.1.war\WEB-INF\classes里面的struts.xml文件,放到SS2H项目的src文件夹内,打开struts-2.1.8.1\apps\struts2-blank-2.1.8.1.war\WEB-INF下的web.xml文件,复制以下内容:
<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>
放到工程目录下web.xml文件的合适位置(<welcome-file-list>的前面)
配置完成后的Web.xml的内容为:
<?xmlversion="1.0"encoding="GBK"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--struts2核心filter,即过滤器-->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
此步骤配置完成的Strust.xml的内容为:
<?xmlversion="1.0"encoding="GBK"?>
<!DOCTYPE strutsPUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!--配置为开发模式-->
<constantname="struts.devMode"value="true"/>
<!--把扩展名配置为action-->
<constantname="struts.action.extension"value="action"/>
<!-- 把主题配置为simple ,自己来控制jsp内的样式-->
<constantname="struts.ui.theme"value="simple"/>
<packagename="default"namespace="/"extends="struts-default">
</package>
<!-- Add packages here -->
</struts>
3.配置Hibernate(使用的是hibernate3.6)
(1)加入jar包,配置hibernate.cfg.xml,*.hbm.xml映射文件。
Jar包(10个):核心包:hibernate3.jar,hibernate-jpa-2.0-api-1.0.0.Final.jar,以及hibernate-distribution-3.6.0.Final\lib\required文件夹下的六个包(必须的包),如下:antlr-2.7.6.jar, commons-collections.jar , dom4j-1.6.1.jar, javassis-3.12.0.jar, jta-1.1.jar, slf4j-api-1.6.1.jar.以及数据库连接池的jar包c3p0:c3p0-0.9.1.jar,mysql数据库驱动jar包:mysql-connector-java-5.1.5-bin.jar。
(2)配置文件:将hibernate-distribution-3.6.0.Final\project\etc文件夹下的log4j.properties文件放到工程的src文件夹下,并且在hibernate-distribution-3.6.0.Final\project\搜索hibernate.cfg.xml,选择搜到的比较大hibernate.cfg.xml拷贝到src目录下。
Hibernate.cfg.xml的内容为:
<?xmlversion='1.0'encoding='GBK'?>
<!DOCTYPE hibernate-configurationPUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings 数据库连接信息-->
<!-- SQL dialect sql方言-->
<propertyname="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<propertyname="connection.driver_class">com.jdbc.mysql.Driver</property>
<propertyname="connection.url">jdbc:mysql:///localhost:itcastoa</property>
<propertyname="connection.username">itcastoa</property>
<propertyname="connection.password">itcastoa</property>
<!--其他配置-->
<!--输入台打印sql语句-->
<propertyname="show_sql">true</property>
<!-- Drop and re-create the database schema on startup自动建表 -->
<propertyname="hbm2ddl.auto">update</property>
<!--导入映射文件 <mappingresource="org/hibernate/tutorial/hbm/Event.hbm.xml"/>-->
</session-factory>
</hibernate-configuration>
4.添加spring
(1)jar包(5个):核心包spring.jar,用于aop的aspectjrt.jar,aspectjweaver.jar,用于实现aop的cglib-nodep-2.1_3.jar,日志的包commons-logging.jar
(2)配置applicationContext.xml/beans.xml:
此时,applicationContext.xml的内容为
<?xmlversion="1.0"encoding="UTF-8"?>
<!--
- Middle tier application context definition for the image database.
-->
<beansxmlns="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-scanbase-package="cn.pofabs.blog"></context:component-scan>
</beans>
(3)在加入struts2-spring-plugin-2.1.8.1.jar之前,单独测试struts2。
测试struts2.
在web.xml中配置TestAction,如下加入:
<package name="default"namespace="/"extends="struts-default"
<!-- 配置测试用的Action,未与Spring整合,class属性写类的全名 -->
<actionname="test"class="cn.pofabs.oa.test.testAction">
<resultname="success">/test.jsp</result>
</action>
</package>
Test.jsp很简单,就不给出了。Action类TestAction的代码为:
package cn.pofabs.oa.test;
import com.opensymphony.xwork2.ActionSupport;
public class TestActionextends ActionSupport{
public String execute()throws Exception{
System.out.println("---->TetsAction execute!");
return"success";
}
}
将项目部署到tomcat,启动服务,浏览器输入: HYPERLINK "http://localhost:8080/SS2H/test.action"http://localhost:8080/SS2H/test.action,运行成功如下:
5.整合struts2与spring(采用在代码中注释的方式)。
(1)在lib文件夹加入jar包struts2-spring-plugin-2.1.8.1.jar,并且在web.xml中加入spring的监听器:
<!--配置Spring的用于初始化容器对象的监听器置于struts2的过滤器前面即可-->
<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)在struts2.xml文件中配置TestAction,testaction的内容如下:
package cn.pofabs.oa.test;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")//多例
publicclassTestActionextends ActionSupport{
public String execute()throws Exception{
System.out.println("---->TetsAction execute!");
return"success";
}
}
struts2.xml中的配置文件为:
<!-- 配置测试用的Action,未与Spring整合,class属性写类的全名 -->
<!-- 当Struts2与Spring整合后,class属性可以写bean的名称 -->
<actionname="test"class="testAction">
<resultname="success">/test.jsp</result>
</action>
启动服务运行,浏览器输入:http://localhost:8080/SS2H/test.action,成功如下显示test.jsp的页面:
6.整合spring(管理事物,对象)与hibernate,目的:管理SessionFactory(只需要一个);声明式事物管理。
(1)在applicationContext.xml中配置以下信息:
<!-- 配置SessionFactory -->
<beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 指定hibernate的配置文件位置 -->
<propertyname="configLocation"value="classpath:hibernate.cfg.xml"></property>
<!-- 配置c3p0数据库连接池 -->
<propertyname="dataSource">
<beanclass="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据连接信息 -->
<propertyname="jdbcUrl"value="${jdbcUrl}"></property>
<propertyname="driverClass"value="${driverClass}"></property>
<propertyname="user"value="${user}"></property>
<propertyname="password"value="${password}"></property>
<!-- 其他配置 -->
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<propertyname="initialPoolSize"value="3"></property>
<!--连接池中保留的最小连接数。Default: 3 -->
<propertyname="minPoolSize"value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<propertyname="maxPoolSize"value="5"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<propertyname="acquireIncrement"value="3"></property>
<!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
<propertyname="maxStatements"value="8"></property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<propertyname="maxStatementsPerConnection"value="5"></property>
<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<propertyname="maxIdleTime"value="1800"></property>
</bean>
</property>
</bean>
然后配置要连接的数据库,在jdbc.properties中配置,jdbc.properties配置代码如下:
jdbcUrl=jdbc:mysql:///oa?useUnicode=true&characterEncoding=utf-8
driverClass= com.mysql.jdbc.Driver
user= oa
password= oa
在applicationContext.xml文件的<beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">位置前面导入外部文件jdbc.properties,加入的代码如下:
<!-- 导入外部的properties文件 -->
<context:property-placeholderlocation="classpath:jdbc.properties"/>
(2)在src文件夹下建立单元测试JUNIT测试类SpringTest如下所示
package cn.itcast.oa.test;
import org.hibernate.SessionFactory;
importorg.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
publicclass SpringTest {
private ApplicationContextac =new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
publicvoid testBean()throws Exception {
TestAction testAction = (TestAction) ac.getBean("testAction");
System.out.println(testAction);
}
// 娴嬭瘯SessionFactory
@Test
publicvoid testSessionFactory()throws Exception {
SessionFactory sessionFactory = (SessionFactory)ac.getBean("sessionFactory");
System.out.println("sessionFactory名字为"+sessionFactory);
}
}
以JUNIT的方式运行SpringTest,输出结果如下:
(3)配置声明式的事务管理(采用注解的方式),在applicationContext.xml文件的</beans>前面加入以下代码:
<!--配置声明式事务管理(采用注解的方式) -->
<beanid="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<tx:annotation-driventransaction-manager="txManager"/>
同时,在SpringTest中加入以下方法:
// 测试事务
@Test
publicvoid testTransaction()throws Exception {
TestService testService = (TestService)ac.getBean("testService");
testService.saveTwoUsers();
}
建立包:cn.pofabs.oa.domain,并在其内建立User.java,User.hbm.xml,如下:
User.java的代码:
package cn.pofabs.oa.domain;
publicclass User{
private Longid;
private Stringname;
publicLong getId() {
returnid;
}
publicvoid setId(Long id) {
this.id = id;
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
}
User.hbm.xml的代码为:
<?xmlversion="1.0"?>
<!DOCTYPE hibernate-mappingPUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mappingpackage="cn.pofabs.oa.domain">
<classname="User"table="oa_user">
<idname="id">
<generatorclass="native"/>
</id>
<propertyname="name"/>
</class>
</hibernate-mapping>
在hibernate.cfg.xml文件中的</session-factory>之前引入映射文件:
<!--导入映射文件-->
<mappingresource="cn/pofabs/oa/domain/User.hbm.xml"/>
在cn.pofabs.oa.test包中建立一个TestService类,代码如下:
package cn.pofabs.oa.test;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.pofabs.oa.domain.User;
//@Service在配置文件中注入service的bean
@Service
publicclass TestService {
//@Resource注入bean的资源
@Resource
private SessionFactorysessionFactory;
@Transactional
publicvoid saveTwoUsers(){
Session session = sessionFactory.getCurrentSession();
session.save(new User());
session.save(new User());
}
}
运行SpringTest,测试成功。
在TestAction中测试三个框架的整合,代码为:
package cn.pofabs.oa.test;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
@Controller
//@Scope("prototype")注入bean的scope,单例还是多例
@Scope("prototype")
publicclassTestActionextends ActionSupport{
@Resource
private TestServicetestService;
publicString execute()throws Exception{
System.out.println("---->TetsAction execute!");
testService.saveTwoUsers();
return"success";
}
}
发布项目启动tomcat访问页面,如下所示:
页面显示如下:
控制台输出:
今天先到这,上班搬砖。下篇将会进一步完善。
此次总结:本次搭建所犯的两次重大错误:一是变量名书写的不一致,如在applicationContext.xml中配置的bean:<beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">,在TestService中书写成了:sessionFactry;二就是在applicationContext.xml中没有加入配置声明式事务管理(采用注解的方式),即一下代码:
<beanid="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<tx:annotation-driventransaction-manager="txManager"/>