本人自己进行的SSH整合,中间遇到不少问题,特此做些总结,仅供参考。

一、使用XML配置:

  1. SSH版本

    • Struts-2.3.31
    • Spring-4.3.5
    • Hibernate-4.2.21
  2. 引入jar包
    • 必须在WEB-INF下添加jar包(其他无效)
    • spring、hibernate及struts2的核心jar包,若有重复的,保留高版本的即可
    • mysql以及数据库连接池的jar包
  3. 编写持久化类及映射文件
  4. 基础applicationContext.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:aop="http://www.springframework.org/schema/aop"
        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.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    </beans>
  5. jdbc.properties
    <!-- 数据库连接池的基本配置 -->
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.url=jdbc\:mysql\://localhost\:3306/ssh
    jdbc.username=root
    jdbc.password=root
  6. Spring整合Hibernate
    <!-- 引入jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 配置dbcp数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClass}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean>
    <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property>
    <!-- 配置hibernate.cfg.xml的路径 --> <!-- <property name="configLocations" value="classpath:hibernate.cfg.xml"/> --> <!-- 不使用hibernate.cfg.xml,由spring配置hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property>
    <!-- 配置.hbm.xml的位置及名称,可以使用通配符 --> <property name="mappingLocations" value="classpath:com/ssh/domain/*.hbm.xml"/> <!-- 配置单独的.hbm.xml --> <property name="mappingResources"> <list> <value>com/ssh/domain/User.hbm.xml</value> </list> </property> </bean>
    <!-- 注入UserDAO --> <bean id="userDao" class="com.ssh.dao.UserDAO"> <property name="sessionFactory" ref="sessionFactory"/> </bean>
    <!--
    Spring自动生成的是代理对象,实现了UserDao接口,不能强转为UserDaoImpl对象 ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); UesrDao dao = (UserDao) context.getBean("userDao");
    //UesrDaoImpl dao = (UserDaoImpl) context.getBean("userDao"); -->
    <!-- 注入UserService --> <bean id="userService" class="com.ssh.dao.UserService"> <property name="userDao" ref="userDao"/> </bean> <!-- 配置 Spring 的声明式事务,需要引入com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar包 --> <!-- 1. 配置数据源DataSource(必须) -->
    <!-- 2. 配置事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>
    <!-- 3. 配置事务建议者(属性) --> <tx:advice id="txAdivce" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice>
    <!-- 4. 配置AOP切面 --> <aop:config> <aop:pointcut expression="execution(* com.ssh.service.*.*(..))" id="pointcut"/> <aop:advisor advice-ref="txAdivce" pointcut-ref="pointcut"/> </aop:config>
    <!-- 5. 不能在hibernate中配置<property name="current_session_context_class">thread</property>,否则Spring不会自动开启事务 -->
  7. Spring整合Struts2
    1. 引入Struts2下的spring插件包:struts2-spring-plugin-2.3.31.jar
    2. 配置web.xml
      <!-- 配置sprin监听器,在服务器启动时初始化IoC容器 -->
      <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <!-- 默认寻找WEB-INF下的applicationContext.xml -->
      <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:applicationContext*.xml</param-value>
      </context-param>
      <!-- 配置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. 在applicationContext.xml中注入Action
      //创建一个SuperActon继承ActionSupport并实现Web元素相关的接口
      <bean id="superAction" class="com.ssh.action.SuperAction" />
      
      <!-- 必须声明 scope 属性为 prototype (非单例) -->
      //创建自己的Action继承SuperAction便可以直接使用request,session等对象
      <bean id="userAction" class="com.ssh.action.UserAction" parent="superAction" scope="prototype">
           <property name="userService" ref="userService"/>
      </bean>
    4. 配置struts.xml
      <!-- class属性的值对应applicationContext.xml中注入的Action的id名 -->
      <action name="user_*" class="userAction" method="{1}">
           <result name="success">/success.jsp</result>
      </action>

二、使用注解+XML配置:

  • 配置struts.xml文件时action的class值要写成Action类的全名
  • 配置 applicationContext.xml:
    <!-- 配置dataSource和sessionFactory -->
    <!-- 注解持久化类的包扫描器 -->
    <property name="packagesToScan" value="com.ssh.entity"></property>
    
    <!-- 开启注解式依赖与注入 -->
    <context:component-scan base-package="com.ssh"/>
    <!-- <context:annotation-config /> -->
    <!-- 开启注解式事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/>
  • 注解类的配置:

    @Controller
    @Scope("prototype")
    public class UserAction extends ActionSupport { @Resource private UserService userService; }
    @Service
    @Transactional public class UserService { @Resource private UserDaoImpl userDao; } @Repository("userDao")
    public class UserDaoImpl implements UserDao{ @Resource private SessionFactory sessionFactory; }
    //若使用继承HibernateDaoSupport的方式,则不能直接注入SessionFactory
    @Repository
    public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
         @Resource
         public void setSuperSessionFactory(SessionFactory sessionFactory) {
               super.setSessionFactory(sessionFactory);
         }
    }

其他问题:

  • 问题:一对多映射时,获取一方对象时同时获取到的是多方的代理对象(延迟加载),在view层调用时抛出异常:org.hibernate.LazyInitializationException: could not initialize proxy - no Session,即代理对象不能被初始化。
  • 原因:在service层添加了事务,事务提交时将session关闭了,所以在view层就不能再使用session获取数据。
  • 解决办法(三种方式):
    1. 将一对多映射中的set中的lazy属性值设为false。
    2. 获取一方对象时使用 迫切左外连接(left join fetch)同时初始化其关联的多方对象。
    3. 在web.xml中配置一个过滤器:OpenSessionInViewFilter
      <!-- 此过滤器必须配置在struts2过滤器的前面 -->
      <filter>
           <filter-name>OpenSessionInViewFilter</filter-name>
           <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
      </filter>
      <filter-mapping>
           <filter-name>OpenSessionInViewFilter</filter-name>
           <url-pattern>*.action<url-pattern>
      </filter-mapping>

以上即为SSH配置的基本过程,若有不足之处还望大家提出自己的想法及意见。

SSH整合总结(xml与注解)的更多相关文章

  1. SSH整合_struts.xml 模板

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "- ...

  2. SSH整合 pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  3. SSH整合主要XML代码

    web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2 ...

  4. ssh整合web.xml过滤器和监听器的配置 .

    延迟加载过滤器 Hibernate 允许对关联对象.属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Session 范围之内进行.如果 Service 层返回一个启用了延迟 ...

  5. Java - 框架之 SSH 整合

                        代码获取 十四. ssh 整合1 - 包 1. Struts jar 包    - Struts-2.xx\apps\stutrs2-blank\WEB-INF ...

  6. Hibernate 注解时 hibernate.hbm.xml的配置方法 以及与SSH整合里的配置方式

    ①纯Hibernate开发: 当你在Bean中写入注解后,需要告诉hibernate哪些类使用了注解. 方法是在hibernate.hbm.xml文件中配置 <!DOCTYPE hibernat ...

  7. ssh整合之七注解结合xml形式

    1.我们之前的纯xml的方式,我们的配置文件很多,我们可以使用注解结合xml的方式进行开发,这样的话,我们的配置文件,会少很多,同时,我们可以直接在类中看到配置,这样,我们就可以快速地搭建一个ssh整 ...

  8. SSH整合之全注解

    SSH整合之全注解 使用注解配置,需要我们额外引入以下jar包

  9. SSH整合,applicationContext.xml中配置hibernate映射文件问题

    今天在applicationContext.xml中配置sessionFactory时遇到了各种头疼的问题,现在总结一下: 1.<property name="mappingDirec ...

随机推荐

  1. MSTP多实例的配置

    MSTP多实例的配置 这次实验主要是为了加强对stp生成树协议中,RP(根端口),DP(指定端口),AP(阻塞端口)的判断方法:虽然很多时候不需要我们人工判断,因为当我们吧所有的配置好之后,然后开启生 ...

  2. Floating IP in OpenStack Neutron

    前言 Floating IP 是相对于Fixed IP而言的,它一般是在VM创建后分配给VM的,可以达到的目的就是,外界可以访问通过这个Floating Ip访问这个VM,VM也可以通过这个IP访问外 ...

  3. 简单的线性M移动平均

    最近在写Python的爬虫爬取全校学生的成绩信息和照片,发现些许问题. python的内存管理机制还没摸透,随着程序的运行,占用内存逐渐增大,料想应该是新开辟的空间未及时释放. 先研究研究算法,为比赛 ...

  4. UWP--页面传值

    //匿名对象 private void Button1_OnClick(object sender, RoutedEventArgs e) { , name = "LBI" }); ...

  5. css基础学习---简单理解

    1:在css中定义图片相对路径 #primary-nav { //相对路径 background: url(../images/alert-overlay.png) repeat-x; height: ...

  6. canvas基础—图形变换

    1.canvas转换方法 1.1canvas转换方法 二.canvas实现图形的中心点旋转 step1:获取canva元素并指定canvas的绘图环境 var canvas=document.getE ...

  7. Linux之uniq命令

    uniq - report or omit repeated lines  省去重复的行 参数: -i  忽略大小写字符的不同 -c  对重复的行进行记数 注意:uniq命令只会对相邻的重复的行进行去 ...

  8. 使用Yeoman generator来规范工程的初始化

    前言 随着开发团队不断发展壮大,在人员增加的同时也带来了协作成本的增加:业务项目越来越多,类型也各不相同.常见的类型有基础组件.业务组件.基于React的业务项目.基于Vue的业务项目等等.如果想要对 ...

  9. echo print print_r的区别

    echo       PHP语句   效率最高    输出一个或者多个字符串 print()    函数       效率高     只能打印出简单类型变量的值(如int,string) print_ ...

  10. 【C++】智能指针详解(二):auto_ptr

    首先,我要声明auto_ptr是一个坑!auto_ptr是一个坑!auto_ptr是一个坑!重要的事情说三遍!!! 通过上文,我们知道智能指针通过对象去管理指针,在构造对象时完成资源的分配及初始化,在 ...