建立一个Web项目,然后导入如下包

struts2包:在struts2-blank.war下的lib目录下,以及struts-2.3.15.1\lib下的struts和spring整合的插件包struts2-spring-plugin-2.3.15.1.jar

hibernate包:hibernate-distribution- 3.6.10.Final\lib\,把required中的所有包都导入进去,以及jpa下的hibernate-jpa-2.0-api- 1.0.1.Final,optional/ c3p0下的JDBC连接池c3p0-0.9.1.jar包,MYSQL的jdbc驱动mysql-connector-java-5.1.7-bin, hibernate的的一个日志系统,hibernate3.jar。

spring2.5:spring

在hibernate-distribution-3.6.10.Final\project\etc下找到一个hibernate.cfg.xml文件,拷贝到项目中的src下,去掉没用的部分。

添加applicationContext.xml文件。

1、整合SHH

首先整合spring和hibernate

applicationContext.xml文件的配置情况:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx.xsd">
  13. <!-- 自动扫描与装配bean -->
  14. <context:component-scan base-package="cn.itcast.oa"></context:component-scan>
  15. <!-- 配置SessionFactory(与Hibernate整合) -->
  16. <!-- 表示下面的变量是从这个配置文件读取的 -->
  17. <context:property-placeholder location="classpath:jdbc.properties"/>
  18. <!-- 在spring中配置了一个叫sessionFactory的bean,类为hibernate中的LocalSessionFactoryBean,这样,spring就和hibernate联系起来了 -->
  19. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  20. <!-- 指定hibernate的配置文件的位置,classpath:hibernate.cfg.xml:配置文件的路径 -->
  21. <property name="configLocation" value="classpath:hibernate.cfg.xml"></property><!-- -->
  22. <property name="dataSource">
  23. <!-- 配置DataSource数据源,这里采用的是c3p0的数据库连接 -->
  24. <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
  25. <property name="jdbcUrl" value="${jdbcUrl}"></property>
  26. <property name="driverClass" value="${driverClass}"></property>
  27. <property name="user" value="${username}"></property>
  28. <property name="password" value="${password}"></property>
  29. <!-- 其他配置 ,具体可以参考c3p0的文档-->
  30. <property name="initialPoolSize" value="3"></property>
  31. <property name="minPoolSize" value="3"></property>
  32. <property name="maxPoolSize" value="15"></property>
  33. <property name="acquireIncrement" value="3"></property>
  34. <property name="maxStatements" value="8"></property>
  35. <property name="maxStatementsPerConnection" value="5"></property>
  36. <property name="maxIdleTime" value="1800"></property>
  37. </bean>
  38. </property>
  39. </bean>
  40. <!-- 配置声明式事物,使用基于注解的方式 -->
  41. <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  42. <property name="sessionFactory" ref="sessionFactory"></property>
  43. </bean>
  44. <!-- 声明式事物管理, 告诉他事物管理是哪一个(transactionManager)-->
  45. <tx:annotation-driven transaction-manager="transactionManager"/>
  46. </beans>

配置hibernate.cfg.xml文件

  1. <!DOCTYPE hibernate-configuration PUBLIC
  2. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  3. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  4. <hibernate-configuration>
  5. <session-factory>
  6. <!-- 数据库信息 -->
  7. <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  8. <property name="show_sql">true</property>
  9. <property name="hbm2ddl.auto">update</property>
  10. <!-- 连接数据库的配置文件写到applicationContext.xml文件中
  11. <property name="connection.url">jdbc:mysql:///OA</property>
  12. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  13. <property name="connection.username">root</property>
  14. <property name="connection.password">root</property>
  15. -->
  16. <!-- 声明映射的配置文件 -->
  17. <mapping resource="cn/itcast/oa/domain/User.hbm.xml" />
  18. </session-factory>
  19. </hibernate-configuration>

Jdbc.properties文件

  1. jdbcUrl=jdbc:mysql:///OA
  2. driverClass=com.mysql.jdbc.Driver
  3. username=root
  4. password=root

到目前为止,我们已经把Hibernate和Spring的框架搭好了,现在我们来做一些测试

建立TestSpring类,这个类用于测试Spring和Hibernate是否整合成功

  1. public class TestSpring {
  2. ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
  3. @Test//执行这个测试方法时,会自动生成数据库中的表
  4. public void testSessionFactory(){
  5. //从applicationContext.xml中获取名为sessionFactory的这个bean
  6. SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
  7. System.out.println(sessionFactory.openSession());//打开session
  8. }
  9. @Test
  10. public void addUser(){
  11. TestService testService = (TestService) ac.getBean("testService");
  12. testService.addUser();
  13. }
  14. }

成功时会打印如下信息:

SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];

ActionQueue[insertions=[] updates=[]deletions=[]

collectionCreations=[] collectionRemovals=[]collectionUpdates=[]])

第二个方法addUser用于测试事物是否能够有效执行

  1. public class User {
  2. private long id;
  3. private String name;
  4. public long getId() {
  5. return id;
  6. }
  7. public void setId(long id) {
  8. this.id = id;
  9. }
  10. public String getName() {
  11. return name;
  12. }
  13. public void setName(String name) {
  14. this.name = name;
  15. }
  16. }

User.hbm.xml

  1. <hibernate-mapping package="cn.itcast.oa.domain">
  2. <!-- 配置的是User对象,对应的表为userTable -->
  3. <class name="User" table="user_Table">
  4. <id name="id" column="id">
  5. <generator class="native"></generator>
  6. </id>
  7. <property name="name"></property>
  8. </class>
  9. </hibernate-mapping>
  1. //@Component相当于在applicationContext中的bean,在bean中,我们添加了bean的id名称
  2. //这里我们也可以使用默认名称(当前类名,首字母小写--testService),也可以添加他的名称
  3. //别名:@Component("别名")
  4. @Component//把TestService作为bean注入到spring容器中
  5. public class TestService {
  6. @Resource//把sessionfactory注入到spring容器中
  7. private SessionFactory sessionFactory;
  8. @Transactional
  9. public void addUser(){
  10. Session session = sessionFactory.getCurrentSession();
  11. session.save(new User());
  12. //  int a=1/0;//执行到这一步时,由于分母为零,异常,因此回滚,但是数据表中的id字段会增加1
  13. session.save(new User());
  14. }
  15. }

先注释掉int a=1/0;执行,去掉注释执行,在注释执行,得到如下结果:

说明当遇到a=1/0之前添加了一个User,执行到a=1/0时,异常回滚了

到目前为止,我们已经成功整合了hibernate和spring,下面我们将整合spring和struts。

在整合的过程中,启动tomcat时,我们遇到了如下的错误提示:

  1. Exception starting filter struts2
  2. Unable to load configuration. - bean - jar:file:/D:/Program%20Files/Apache%20Software%20Foundation/Tomcat%206.0/webapps/SSH/WEB-INF/lib/struts2-core-2.3.15.1.jar!/struts-default.xml:68:184
  3. at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:502)

提示的消息是说不能加载struts2-core-2.3.15.1.jar/struts-default.xml这个配置文件。

解决:

由于版本的不一致,我们在发布的时候导致了出现同一个文件的不同版本,我这里是出现了struts2-core-2.3.15.1.jar和struts2-core-2.3.8.jar这两个文件同时在项目中,如果只在项目中删除的话,不一定能够完全删除,需要在D:\Program
Files\Apache Software Foundation\Tomcat6.0\webapps\SSH\WEB-INF\lib下删除其中的一个文件,我这里删除的是struts2-core-2.3.15.1.jar,我如果删除struts2-core-2.3.8.jar,貌似也会出现问题?可能是版本不一致的原因,不懂。。。

  1. //这个bean的生命周期默认值为singleton(单例),但是这里由于每个bean返回的是一个实例,
  2. //所以不能使用singleton模式,代表每次返回一个action的实例
  3. @Scope("prototype")
  4. // @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
  5. // @Service 通常作用在业务层,但是目前该功能与 @Component 相同。
  6. // @Constroller 通常作用在控制层,但是目前该功能与 @Component相同。
  7. @Controller
  8. public class TestAction extends ActionSupport {
  9. @Resource
  10. //把testService作为bean注入到spring容器中
  11. private TestService testService;
  12. public String execute() throws Exception {
  13. System.out.println("TestAction.execute()");
  14. testService.addUser();
  15. return "success";
  16. }
  17. }

Struts.xml文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  4. "http://struts.apache.org/dtds/struts-2.3.dtd">
  5. <struts>
  6. <constant name="struts.devMode" value="true" /><!-- 设置为开发模式 -->
  7. <package name="default" namespace="/" extends="struts-default">
  8. <!-- Struts2与Spring整合后,class属性中写的是bean的名称 -->
  9. <action name="testAction" class="testAction">
  10. <result name="success">/test.jsp</result>
  11. </action>
  12. </package>
  13. <!-- Add packages here -->
  14. </struts>

最后一步:整合spring和web.xml,也就是需要对web.xml文件做一下配置,如下所示:

  1. <!--
  2. ContextLoaderListener的作用就是启动Web容器时,
  3. 自动装配ApplicationContext的配置信息。
  4. 因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,
  5. 启动容器时,就会默认执行它实现的方法。
  6. 在ContextLoaderListener中关联了ContextLoader这个类,
  7. 所以整个加载配置过程由ContextLoader来完成。
  8. applicationContext.xml的文件位置就可以有两种默认实现:
  9. 第一种:直接将之放到/WEB-INF下,之在web.xml中声明一个listener
  10. 第二种:将之放到classpath下,但是此时要在web.xml中加入<context-param>,
  11. 用它来指明你的applicationContext.xml的位置以供web容器来加载。
  12. 按照 Struts2 整合spring的官方给出的档案,写成:
  13. <context-param>
  14. <param-name>contextConfigLocation</param-name>
  15. <param-value>
  16. /WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml
  17. </param-value>
  18. </context-param>
  19. -->
  20. ===========================这是添加的内容=============================
  21. <!-- 把spring交给web.xml,配置spring的初始化监听器ContextLoaderListener -->
  22. <listener>
  23. <listener-class>
  24. <!-- 执行这句话时,会自动装配ApplicationContext(Spring) -->
  25. org.springframework.web.context.ContextLoaderListener
  26. </listener-class>
  27. </listener>
  28. <context-param>
  29. <param-name>contextConfigLocation</param-name>
  30. <param-value>classpath:applicationContext.xml</param-value>
  31. </context-param>
  32. ====================================================================
  33. <!-- 从struts2中的
  34. 配置Struts2的过滤器
  35. -->
  36. <filter>
  37. <filter-name>struts2</filter-name>
  38. <filter-class>
  39. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  40. </filter-class>
  41. </filter>
  42. <filter-mapping>
  43. <filter-name>struts2</filter-name>
  44. <url-pattern>/*</url-pattern>
  45. </filter-mapping>
  46. <welcome-file-list>
  47. <welcome-file>index.jsp</welcome-file>
  48. </welcome-file-list>

测试的页面

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  3. <html>
  4. <head>
  5. </head>
  6. <body>
  7. Spring和struts2整合成功。
  8. </body>
  9. </html>

测试成功的页面:

SHH框架的搭建的更多相关文章

  1. 基于C/S架构的3D对战网络游戏C++框架 _06搭建C/S架构的基本通信框架(尚未写完会重新编辑后再发出)

    本系列博客主要是以对战游戏为背景介绍3D对战网络游戏常用的开发技术以及C++高级编程技巧,有了这些知识,就可以开发出中小型游戏项目或3D工业仿真项目. 笔者将分为以下三个部分向大家介绍(每日更新): ...

  2. 基于C/S架构的3D对战网络游戏C++框架 _05搭建系统开发环境与Boost智能指针、内存池初步了解

    本系列博客主要是以对战游戏为背景介绍3D对战网络游戏常用的开发技术以及C++高级编程技巧,有了这些知识,就可以开发出中小型游戏项目或3D工业仿真项目. 笔者将分为以下三个部分向大家介绍(每日更新): ...

  3. Spring+SpringMvc+Mybatis框架集成搭建教程

    一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼 ...

  4. eclipse中SSH三大框架环境搭建<三>

    相关链接: eclipse中SSH三大框架环境搭建<一> eclipse中SSH三大框架环境搭建<二> 引言:通过上两篇文章我们已经可以掌握struts2和spring的环境的 ...

  5. eclipse中SSH三大框架环境搭建<二>

    通过上一篇博客我们可以轻松搭建strtus2的环境,接下来由我来继续介绍spring的环境搭建以及spring注入的简单使用 相关链接:eclipse中SSH三大k框架环境搭建<一> ec ...

  6. Struts2+Spring+Hibernate(SSH)框架的搭建

    首先需要下载struts2 ,spring4,hibernate5  的资源包; struts2资源包下载路径:http://www.apache.org/spring资源包下载路径:http://p ...

  7. Ext.NET 4.1 系统框架的搭建(后台) 附源码

    Ext.NET 4.1 系统框架的搭建(后台) 附源码 代码运行环境:.net 4.5  VS2013 (代码可直接编译运行) 预览图: 分析图: 上面系统的构建包括三块区域:North.West和C ...

  8. eclipse中SSH三大框架环境搭建<一>

    这里先简单介绍一下我用的三大框架版本以及下载地址 相关链接:eclipse中SSH三大框架环境搭建<二> eclipse中SSH三大框架环境搭建<三> struts-2.3.3 ...

  9. iOS基础框架的搭建/国际化操作

    1.基础框架的搭建 1.1 pod引入常用的第三方类库 1.2 创建基础文件夹结构/目录结构 Resource———存放声音/图片/xib/storyboard 等资源文件 Define——宏定义, ...

随机推荐

  1. 用python写一个类似于linux中的tree

    import os filePath = 'g:/File' j = 0 # 查找的深度计数 def tree(filePath,j): dir_now = os.listdir(filePath) ...

  2. HTML+CSS : H5+CSS3

    HTML5语义化标签: header nav(导航) article section(章节) aside(侧边栏) footer------------------------------------ ...

  3. Redis------Set集合类型

    set是string类型的无序集合 类比:你的朋友不能超过2的32次方-1个元素 基本添加删除操作 取并集 取交集 取差集 注意:每个元素的各个元素不能重复 应用场合:qq好友推荐‘ TomFri 的 ...

  4. PHP表单安全过滤和防注入 htmlspecialchars() 和test_input()

    什么是 htmlspecialchars() 函数? htmlspecialchars() 函数把特殊字符转换为 HTML 实体.这意味着 < 和 > 之类的 HTML 字符会被替换为 & ...

  5. photoshop入门笔记1:PS的快捷键

    PS部分快捷键: 1.魔棒的作用:比较快捷的抠图工具,对于一些分界线比较明显的图像,通过魔棒工具可以很快速的将图像抠出,魔棒的作用是可以知道你点击的那个地方的颜色,并自动获取附近区域相同的颜色,使它们 ...

  6. Python装饰器探究——装饰器参数

    Table of Contents 1. 探究装饰器参数 1.1. 编写传参的装饰器 1.2. 理解传参的装饰器 1.3. 传参和不传参的兼容 2. 参考资料 探究装饰器参数 编写传参的装饰器 通常我 ...

  7. TP5 中出现 No input file specified

    之前用php5.4 更新至php7之后原tp5项目出现 No input file specified 修改方法: 打开public目录下的.htaccess文件,把:RewriteRule ^(.* ...

  8. Django将queryset转为json对象

  9. PJSIP-PJLIB(samples) (the usage of the pjlib lib) (eg:string/I/O)

    Here are some samples about  PJLIB! PJLIB is the basic lib of PJSIP, so we need master the lib first ...

  10. 《1024伐木累》-小白篇之丽jie(结束篇)-总章节六

    往期回顾:  机缘巧合,月侠发现了老王和他心仪女孩儿的秘密,这让他倍感愤怒,一年以后,丽姐又在去往老王家的路上,这让月侠感到历史即将重新上演,他想拦住丽姐,可恰巧丽姐手机没电,失去了联系. 小序 有人 ...