SHH框架的搭建

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

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

hibernate包:hibernate-distribution- 3.6.10.Finallib,把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.Finalprojectetc下找到一个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.   
  14. <!-- 自动扫描与装配bean -->  
  15. <context:component-scan base-package="cn.itcast.oa"></context:component-scan>  
  16.   
  17. <!-- 配置SessionFactory(与Hibernate整合) -->  
  18. <!-- 表示下面的变量是从这个配置文件读取的 -->  
  19. <context:property-placeholder location="classpath:jdbc.properties"/>  
  20.   
  21. <!-- 在spring中配置了一个叫sessionFactory的bean,类为hibernate中的LocalSessionFactoryBean,这样,spring就和hibernate联系起来了 -->  
  22. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  23.     <!-- 指定hibernate的配置文件的位置,classpath:hibernate.cfg.xml:配置文件的路径 -->  
  24.     <property name="configLocation" value="classpath:hibernate.cfg.xml"></property><!-- -->  
  25.       
  26.     <property name="dataSource">  
  27.         <!-- 配置DataSource数据源,这里采用的是c3p0的数据库连接 -->  
  28.         <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  29.             <property name="jdbcUrl" value="${jdbcUrl}"></property>  
  30.             <property name="driverClass" value="${driverClass}"></property>  
  31.             <property name="user" value="${username}"></property>  
  32.             <property name="password" value="${password}"></property>  
  33.               
  34.             <!-- 其他配置 ,具体可以参考c3p0的文档-->  
  35.             <property name="initialPoolSize" value="3"></property>  
  36.             <property name="minPoolSize" value="3"></property>  
  37.             <property name="maxPoolSize" value="15"></property>  
  38.             <property name="acquireIncrement" value="3"></property>  
  39.             <property name="maxStatements" value="8"></property>  
  40.             <property name="maxStatementsPerConnection" value="5"></property>  
  41.             <property name="maxIdleTime" value="1800"></property>  
  42.         </bean>  
  43.     </property>  
  44. </bean>     
  45.   
  46. <!-- 配置声明式事物,使用基于注解的方式 -->  
  47. <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  48.     <property name="sessionFactory" ref="sessionFactory"></property>  
  49. </bean>  
  50. <!-- 声明式事物管理, 告诉他事物管理是哪一个(transactionManager)-->  
  51. <tx:annotation-driven transaction-manager="transactionManager"/>    
  52. </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.   
  5. <hibernate-configuration>  
  6. <session-factory>  
  7.     <!-- 数据库信息 -->  
  8.     <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>  
  9.     <property name="show_sql">true</property>  
  10.     <property name="hbm2ddl.auto">update</property>  
  11.     <!-- 连接数据库的配置文件写到applicationContext.xml文件中  
  12.         <property name="connection.url">jdbc:mysql:///OA</property>  
  13.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
  14.         <property name="connection.username">root</property>  
  15.         <property name="connection.password">root</property>  
  16.     -->  
  17.   
  18.     <!-- 声明映射的配置文件 -->  
  19.     <mapping resource="cn/itcast/oa/domain/User.hbm.xml" />  
  20. </session-factory>  
  21. </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.       
  4.     @Test//执行这个测试方法时,会自动生成数据库中的表  
  5.     public void testSessionFactory(){  
  6.         //从applicationContext.xml中获取名为sessionFactory的这个bean  
  7.         SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");  
  8.         System.out.println(sessionFactory.openSession());//打开session  
  9.     }  
  10.     @Test  
  11.     public void addUser(){  
  12.         TestService testService = (TestService) ac.getBean("testService");  
  13.         testService.addUser();  
  14.     }  
  15. }  

成功时会打印如下信息:

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.       
  9.     @Transactional  
  10.     public void addUser(){  
  11.         Session session = sessionFactory.getCurrentSession();  
  12.         session.save(new User());  
  13. //  int a=1/0;//执行到这一步时,由于分母为零,异常,因此回滚,但是数据表中的id字段会增加1  
  14.         session.save(new User());  
  15.     }  
  16. }  


先注释掉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 FilesApache Software FoundationTomcat6.0webappsSSHWEB-INFlib下删除其中的一个文件,我这里删除的是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.       
  13.     public String execute() throws Exception {  
  14.         System.out.println("TestAction.execute()");  
  15.         testService.addUser();  
  16.         return "success";  
  17.     }     
  18. }  

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.   
  6. <struts>  
  7.     <constant name="struts.devMode" value="true" /><!-- 设置为开发模式 -->  
  8.     <package name="default" namespace="/" extends="struts-default">  
  9.         <!-- Struts2与Spring整合后,class属性中写的是bean的名称 -->  
  10.         <action name="testAction" class="testAction">  
  11.             <result name="success">/test.jsp</result>  
  12.         </action>  
  13.     </package>  
  14.     <!-- Add packages here -->      
  15. </struts>  

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

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

测试的页面

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

测试成功的页面:

原文地址:https://www.cnblogs.com/jiafuwei/p/4430620.html