使用Maven构建SSH

本人自己进行的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配置的基本过程,若有不足之处还望大家提出自己的想法及意见。

上一篇:Android开发中的PhoneGap基本使用


下一篇:UVA 133“The Dole Queue”(循环报数处理技巧)