Spring学习笔记(六)—— SSH整合

一、整合原理

  

二、整合步骤

2.1 导包

【hibernate】

  • hibernate/lib/required
  • hibernate/lib/jpa
  • 数据库驱动

【struts2】

  • struts-blank.war/WEB-INF/lib/*(注意:javassist-3.18.1-GA.jar包与hibernate中的重复,删除版本低的
  • struts整合spring插件包

    (注意:这个包一旦导入,那么struts2在启动时就会寻找spring容器,如果你导入了这个包,却没有配置spring容器,那么项目启动的时候就会抛出异常)

【spring】

  • 基本(4+2):core、beans、context、expression、logging、log4j
  • 整合web的包:spring-web
  • 整合aop(4个):spring-aop、spring-aspect、aop联盟、aopweaving
  • 整合Hibernate和事务(4个):spring-jdbc、spring-tx、c3p0、spring-orm
  • junit4测试包:spring-test

2.2 单独配置spring容器

2.2.1 创建配置文件applicationContext.xml,并导入约束

  

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans" 
    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-4.2.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.2.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
    
    
</beans>

2.2.2 在web.xml中配置spring随项目启动

<!-- 让spring随web启动而启动的监听器 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置spring配置文件的位置参数 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

2.3 单独配置struts2

2.3.1 配置struts2主配置文件struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- 配置一个包:package -->
    <package name="crm" namespace="/" extends="struts-default">
        <!-- 配置Action -->
        <action name="UserAction_*" class="cn.itcast.web.action.UserAction" method="{1}">
            <!-- 配置结果页面的跳转 -->
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>

2.3.2 配置struts2核心过滤器到web.xml

<!-- 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>

2.4 struts2与spring整合

2.4.1  在struts.xml中配置常量

<!-- # struts.objectFactory = spring  将antion的创建交给spring容器
    struts.objectFactory.spring.autoWire = name  spring负责装配Action的依赖属性
 -->
<constant name="struts.objectFactory" value="spring"></constant>

2.4.2 整合

  • 方案1:struts2自己创建action,spring负责组装依赖属性(不推荐,最好由spring完整管理action的生命周期.spring中的功能才能应用到Action上)
    <!-- 整合方案1:class属性上仍然配置action的完整类名
         struts2仍然创建action,由spring负责组装action中的依赖属性
      -->
     <action name="UserAction_*" class="cn.itcast.web.action.UserAction" method="{1}">
         <result name="success">/success.jsp</result>
     </action>
  • 方案2:spring负责创建action以及组装。struts.xml:
    <!-- 整合方案2:class属性上填写spring中action对象的BeanName
            完全由spring管理action生命周期,包括Action的创建
            注意:需要手动组装依赖属性
     -->
     <action name="UserAction_*" class="userAction" method="{1}">
         <result name="success">/success.jsp</result>
     </action>

     applicationContext.xml

    <!-- action -->
    <!-- 注意:Action对象的作用范围一定是多例的,这样才符合struts2架构 -->
    <bean name="userAction" class="cn.itcast.web.action.UserAction" scope="prototype">
        <property name="userService" ref="userService"></property>
    </bean>

2.5 单独配置hibernate

2.5.1 导入实体类&orm元数据

  

2.5.2 配置主配置文件hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    
         <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///crm</property>
         <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
         <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">root</property>
        <!-- 数据库方言
            注意: MYSQL在选择方言时,请选择最短的方言.
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
        <property name="hibernate.format_sql">true</property>
        <!-- 
        自动导出表结构. 自动建表
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
         
         <!-- 引入实体配置文件 -->
        <mapping resource="cn/itcast/domain/Customer.hbm.xml" />
        <mapping resource="cn/itcast/domain/LinkMan.hbm.xml" />
        <mapping resource="cn/itcast/domain/User.hbm.xml" />
        
    </session-factory>
</hibernate-configuration>

2.6 spring整合hibernate

2.6.1 在spring中配置sessionFactory

  • 方案一:仍然使用外部的hibernate.cfg.xml配置信息
    <!-- 将SessionFactory配置到spring容器中 -->
    <!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
    <bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>
  • 方案二:在spring配置中配置hibernate配置信息
    <!-- 将SessionFactory配置到spring容器中 -->
    <!-- 加载配置方案2:在spring配置中配置hibernate配置信息 -->
    <bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 配置hibernate基本信息 -->
        <property name="hibernateProperties">
            <props>
                <!-- 必选配置 -->
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.url">jdbc:mysql:///crm</prop>
                <prop key="hibernate.connection.username">root</prop>
                <prop key="hibernate.connection.password">root</prop>
                <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>
        
        <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
        <property name="mappingDirectoryLocations" value="classpath:cn/itcast/domain"></property>
    </bean>

2.6.2 操作数据库

  • Dao类创建:继承HibernateDaoSupport
    // HibernateDaoSupport 为dao注入sessionFactory
    public class UserDaoImpl extends HibernateDaoSupportimplements UserDao{
    
        @Override
        public User getByUserCode(final String usercode) {
            // HQL
            return getHibernateTemplate().execute(new HibernateCallback<User>() {
                @Override
                public User doInHibernate(Session session) throws HibernateException {
                    Query query = session.createQuery("from User where user_code=?");
                    query.setParameter(0, usercode);
                    User user = (User) query.uniqueResult();
                    return user;
                }
            });
            
            // Criteria
            /*DetachedCriteria dc = DetachedCriteria.forClass(User.class);
            dc.add(Restrictions.eq("user_code", usercode));
            List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);
            if(list!=null&&list.size()>0){
                return list.get(0);
            }else{
                return null;
            }*/
        }
    }
  • spring中配置dao
    <!-- dao -->
    <bean name="userDao" class="cn.itcast.dao.impl.UserDaoImpl">
        <!-- 注入sessionFactory -->
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

2.7 spring整合c3p0连接池

2.7.1 配置db.properties

jdbc.jdbcUrl=jdbc:mysql:///crm
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

2.7.2 引入连接池到spring中

<!-- 读取db.properties文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>

2.7.3 将连接池注入给SessionFactory

<!-- 将SessionFactory配置到spring容器中 -->
<bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <!-- 将连接池注入到sessionFactory,hibernate会通过连接池获得连接 -->
  <property name="dataSource" ref="dataSource"></property>
    ...
</bean>

2.8 spring的AOP事务

  详细步骤见Spring学习笔记(四)—— Spring中的AOP

三、扩大session作用范围

  为了避免使用懒加载时出现no-session问题,在web.xml中配置openSessionInViewFilter来扩大session的作用范围

<!-- 扩大session的作用范围 注意:任何filter一定要在struts的filter之前调用 -->
<filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
原文地址:https://www.cnblogs.com/yft-javaNotes/p/10307530.html