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

项目环境:

  • struts-2.3.31 + spring-4.3.7 + hibernate-4.2.21 + maven-3.3.9 + mysql5.7

首先使用maven引入相关依赖:

  • pom.xml:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.mbq.ssh-maven</groupId>
        <artifactId>ssh-maven</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <properties>
            <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
        </properties>
    
        <!-- spring的依赖管理器,统一版本号 -->
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-framework-bom</artifactId>
                    <version>4.3.7.RELEASE</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <dependencies>
            <!-- web工程所需的依赖 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>
    
            <!-- spring整合hibernate的依赖 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.2.21.Final</version>
            </dependency>
            <!-- spring使用xml方式声明式事务所需的依赖 -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.10</version>
            </dependency>
    
            <!-- c3p0数据库连接池的依赖 -->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </dependency>
    
            <!-- mysql数据库的依赖 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.39</version>
            </dependency>
    
            <!-- struts2的依赖 -->
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-core</artifactId>
                <version>2.3.31</version>
                <!-- 去除与hibernate重复的依赖 -->
                <exclusions>
                    <exclusion>
                        <groupId>javassist</groupId>
                        <artifactId>javassist</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <!-- spring整合struts2的依赖 -->
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-spring-plugin</artifactId>
                <version>2.3.31</version>
            </dependency>
    
        </dependencies>
    
    </project>

一、使用XML配置:

1. 搭建Hibernate环境:

  • hibernate.cfg.xml(可选,在spring中配置)
  • 映射文件.hbm.xml或使用注解

2. Spring整合Hibernate:

  • jdbc.properties

    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.url=jdbc\:mysql\://localhost\:3306/ssh?useUnicode\=true&characterEncoding\=utf8
    jdbc.username=root
    jdbc.password=root
  • 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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    
      <!-- 引入jdbc.properties -->
      <context:property-placeholder location="classpath:jdbc.properties"/>
    
      <!-- 注入c3p0数据源 -->
      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
      </bean>
    
      <!-- 注入Hibernate的SessionFactory对象 -->
      <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    
        <!-- 配置Hibernate的全局配置文件 -->
        <!-- <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/entity/*.hbm.xml"/>
    
          <!-- 配置单独的.hbm.xml -->
          <!-- <property name="mappingResources">
                <list>
                     <value>com/ssh/entity/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 的声明式事务,需要引入aspectjweaver的依赖 -->
      <!-- 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不会自动开启事务 -->
    
    </beans>

3. Spring整合Struts2

  • 引入依赖:struts2-spring-plugin
  • 在web.xml中配置struts2的核心过滤器及spring的监听器
    <!-- 配置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>
  • 在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>
  • 配置struts.xml

    <!-- class属性的值对应beans.xml中注入的Action的id名 -->
    <action name="user_*" class="userAction" method="{1}">
      <result name="success">/success.jsp</result>
    </action>

二、使用注解+XML配置:

  • 以下仅为不同于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"/>
    
    <!-- 开启注解式事务 -->
    <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);
        }
    }    

 

LazyInitializationException问题:

  • 问题:一对多映射时,获取一方对象时同时获取到的是多方的代理对象(延迟加载),在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配置的基本过程,若有不足之处还望大家提出自己的想法及意见。

使用Maven构建SSH的更多相关文章

  1. maven构建ssh工程

    1.1 需求 在web工程的基础上实现ssh工程的创建,规范依赖管理. 1.2 数据库环境 使用之前学习hibernate创建的数据库:    1.3 创建父工程 选择创建Maven Project ...

  2. Maven的学习资料收集--(九) 构建SSH项目以及专栏maven

    在这里整合一下,使用Maven构建一个SSH项目 1.新建一个Web项目 可以参照前面的博客 2.添加依赖,修改pom.xml <project xmlns="http://maven ...

  3. maven 构建spring ssh mybatis 配置

    详情参与 http://blog.csdn.net/yuguiyang1990/article/details/8811817 前面我们使用Maven构建了Struts2项目,这里我们来试一下Hibe ...

  4. maven(二) maven项目构建ssh工程(父工程与子模块的拆分与聚合)

    前一节我们明白了maven是个什么玩意,这一节就来讲讲他的一个重要的应用场景,也就是通过maven将一个ssh项目分割为不同的几个部分独立开发,很重要,加油 --WH 一.maven父工程与子模块的拆 ...

  5. 转帖:maven(二) maven项目构建ssh工程(父工程与子模块的拆分与聚合)

    出处:http://www.cnblogs.com/whgk/p/7121336.html 前一节我们明白了maven是个什么玩意,这一节就来讲讲他的一个重要的应用场景,也就是通过maven将一个ss ...

  6. Jenkins日常运维笔记-重启数据覆盖问题、迁移、基于java代码发版(maven构建)

    之前在公司机房部署了一套jenkins环境,现需要迁移至IDC机房服务器上,迁移过程中记录了一些细节:1)jenkins默认的主目录放在当前用户家目录路径下的.jenkins目录中.如jenkins使 ...

  7. [原]Jenkins(七)---jenkins项目编译测试发布由maven构建的web项目

    /** * lihaibo * 文章内容都是根据自己工作情况实践得出. * 版权声明:本博客欢迎转发,但请保留原作者信息! http://www.cnblogs.com/horizonli/p/533 ...

  8. maven构建SSM项目

    对于小型项目来说,使用默认的maven配置项目即可,可是现在分布式项目越来越多,如果巧妙的使用maven部署项目这成了关键. maven的pom.jar.war: 要正确部署得对maven的pom.w ...

  9. Maven学习- 使用Maven构建Web项目

    从网上查了一些资料,才算明白(也就是怎么操作吧),怎么使用Maven构建一个Web项目,找到一篇文档,主要都是从这里学到的: 下载地址:使用Eclipse构建Maven的Web项目.docx 现自己在 ...

随机推荐

  1. Vue开源项目库汇总

    最近做了一个Vue开源项目库汇总,里面集合了OpenDigg 上的优质的Vue开源项目库,方便移动开发人员便捷的找到自己需要的项目工具等,感兴趣的可以到GitHub上给个star. UI组件 elem ...

  2. Javascript把数据从一个页面的层传递到另一个页面层里面

    背景:昨天头脑发热投了某一家国企的计算机类岗位(说是有前端岗位),通过找同学内推,虽然也笔试了一大堆题目(行测题,计算机网络,http协议,英译汉,古诗文默写,自己把品质排序并且进行200字以上的阐述 ...

  3. .NET的SqlHelper应用代码

    首先需要引用命名空间 ,同时也需要右击'引用' --> '添加引用' --> '程序集' --> '框架' --> 'System.Configuration',SqlHelp ...

  4. 深入理解Python中协程的应用机制: 使用纯Python来实现一个操作系统吧!!

    本文参考:http://www.dabeaz.com/coroutines/   作者:David Beazley 缘起: 本人最近在学习python的协程.偶然发现了David Beazley的co ...

  5. 专题:DUILIB Win32 透明效果

    Win32 透明效果相关基础知识 Layered Windows 分层窗口.这是Windows2000开始引入的概念,重新定义了窗口的Hit Testing方法,以前都是把窗口按rectangle的方 ...

  6. Objective-C日记-之NSPredicate

    谓语:NSPredicate 1,概述: 用于设置指定的过滤器的条件,通俗的理解就是设置选择的条件,再对指定的对象应用这个条件 2,用法: a,首先设置谓语. NSPredicate *predica ...

  7. 1615: [Usaco2008 Mar]The Loathesome Hay Baler麻烦的干草打包机

    1615: [Usaco2008 Mar]The Loathesome Hay Baler麻烦的干草打包机 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit:  ...

  8. c++ 构造函数以及explicit 关键字的使用

    关于构造函数中的隐式转换: 在一个类所定义的构造函数中,存在如下的用法: #pragma once #ifndef __EXERCISE__ #define __EXERCISE__ #include ...

  9. 谷歌开源图片压缩算法Guetzli实测体验报告

    谷歌大神又出开源新技术啦,这次是对JPEG格式的图片采用全新算法重新编码,输出的图片还是JPEG但是图片大小明显缩小,而质量不但没有损失,甚至还更加优化,速速来体验一把. 一.环境安装 下载谷歌开源软 ...

  10. Mongo-Connector 安装及使用文档

    # Mongo-Connector 安装及使用文档 ------ > * 工具介绍> * 安装前准备> * 安装步骤> * 命令详解> * 有可能的坑> * 其他文 ...