JavaWeb学习:SSH解析

一、SSH:Struts2、Spring、Hibernate三个框架的整合。

  Struts2:模型与视图的数据交互

  Spring:一个分层的SE/EE一站式轻量级开源框架

    1、方便解耦,简化开发

      通过Spring提供的IOC容器,可以将对象之间依赖关系交由Spring控制,以降低程序过度耦合。

    2、AOP编程的支持

    3、声明式事务的支持

    4、方便集成各种优秀框架

  Hibernate:是一个开放源代码的ORM(对象关系关系映射)框架

    ORM:Object Relational Mapping(对象关系映射)。将Java中的对象与关系型数据库中的表建立一种映射关系,从而操作对象就可以操作数据库中的表。

二、SSH整合方式

  1、spring提供了一个ContextLoaderListener核心监听器加载配置文件(applicationContext.xml)

    1.1、web.xml添加监听      

1     <listener>
2         <!-- 配置spring-web.jar提供的监听器,此监听器 可以在服务器启动时 初始化Ioc容器。 初始化Ioc容器(applicationContext.xml) 
3             1.告诉监听器 此容器的位置:context-param 2.默认约定的位置 :WEB-INF/applicationContext.xml -->
4         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
5     </listener>

    1.2、指定配置文件(applicationContext.xml)位置

    <!-- 指定 Ioc容器(就是applicationContext.xml)的位置 -->
    <context-param>
        <!-- 监听器的父类ContextLoader中有一个属性contextConfigLocation, 该属性值 保存着 容器配置文件applicationContext.xml的位置 -->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

  2、所有请求都必须通过Struts2过滤器StrutsPrepareAndExecuteFilter

    2.1、web.xml 添加Struts2过滤器

    <!-- Struts2的核心过滤器 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>

    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  3、Spring整合Hibernate

    了解HIbernate的配置文件(hibernate.cfg.xml和类名.hbm.xml--类和数据表的映射关系),其具体作用,Spring如管理

      hibernate.cfg.xml(主要配置session-factory节点,其内容是数据库相关配置信息,其作用负责初始化Hibernate)

<?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.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=HibernateDB;</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password">AAA@111</property>
        
        <!-- 配置Hibernate的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
        <!-- 可选配置start -->
        <!-- 控制台打印sql语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 控制台打印sql语句 格式化-->
        <property name="hibernate.format_sql">true</property>
        
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 
        事务隔离级别
            1-Read uncommitted 
            2-Read committed
            4-Repeatable read
            8-Serializable
         -->
        <property name="hibernate.connection.isolation">2</property>
        
        <!-- 可选配置end -->
        
        <!-- 配置C3P0连接池 -->
        <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <!--在连接池中可用的数据库连接的最少数目 -->
        <property name="c3p0.min_size">5</property>
        <!--在连接池中所有数据库连接的最大数目  -->
        <property name="c3p0.max_size">20</property>
        <!--设定数据库连接的过期时间,以秒为单位,
        如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
        <property name="c3p0.timeout">120</property>
         <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
        <property name="c3p0.idle_test_period">3000</property>
        
        <!-- 配置映射 -->
        <mapping resource="com/xxx/ssh/domain/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

    sessionFactory 作用:用于管理Hibernate会话(session)的对象,你可以把sessionFactory当成里面有一个DataSource;这个对象创建了,hibernate才真正和数据库连接上了。SessionFactory是线程安全的,并且创建和销毁需要消耗比较大的资源,所以整个应用里面针对一个数据库只需要一个SessionFactory

    public void demo1() {
    // 1.加载Hibernate的配置文件Hibernate.cfg.xml
    // 1.1.属性文件加载
    Configuration configuration=new Configuration().configure();
    // 2.获取SessionFactory对象  类似JDBC连接池
    SessionFactory factory=configuration.buildSessionFactory();
    // 3.获取Session对象    类似JDBC中Connection
    Session session=factory.openSession();
    // 4.开启事务(Hibernate版本5不用手动开启事务,要兼容版本3需要手动开启事务)
    Transaction transaction=session.beginTransaction();
    // 5.编写代码
    Customer customer=new Customer();
    customer.setCust_name("zhang");
    
    session.save(customer);
    // 6.提交事务
    transaction.commit();
    // 7.资源释放
    session.close();
    }

    通过以上代码,可以知道操作数据库,就必须获取Session对象,Session对象是SessionFactory对象创建,SessionFactory对象是通过加载配置hibernate.cfg.xml,生成配置文件对象,并通过此对象创建SessionFactory,所以Spring想要整合Hibernate就需要hibernate.cfg.xml配置文件,再看hibernate.cfg.xml配置文件内容都是在session-factory节点下配置。

    Spring管理HIbernate配置文件两种方式:

      方式一:applicationContext.xml中加载hibernate.cfg.xml文件

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 加载hibernate配置文件 -->
        <property name="configLocations" value="classpath:hibernate.cfg.xml"/>
    </bean>

      方式二:在applicationContext.xml中直接配置hibernate.cfg.xml文件中的内容

        jdbc.properties文件内容

jdbc.driverClass=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;databaseName=HibernateDB;
jdbc.username=sa
jdbc.password=AAA@111

        applicationContext.xml添加内容,最终目的:管理sessionFactory对象。

<!-- 引入数据库连接属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 配置C3P0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        
        <!-- 注入连接池 -->
        <property name="dataSource" ref="dataSource"/>

        <!-- 配置Hibernate的相关属性
                private Properties hibernateProperties;对应使用<props>标签
         -->
        <property name="hibernateProperties">
            <props>
                <!-- 方言 -->
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
                <!-- 控制台打印sql语句 -->
                <prop key="hibernate.show_sql">true</prop>
                <!-- 控制台打印sql语句 格式化-->
                <prop key="hibernate.format_sql">true</prop>
                <!-- 自动创建修改表 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        
        <!-- 配置映射 -->
        <mapping resource="com/xxx/ssh/domain/Customer.hbm.xml"/>
 </bean>

  以上配置完成后,代码中就可以通过继承HibernateDaoSupport,其内部有setSessionFactory方法回去创建HibernateTemplate对象,可以使用此对象中的方法操作数据库了。

public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {

    @Override
    public void save(Customer customer) {
    System.out.println("CustomerDaoImpl的save方法执行了");
    this.getHibernateTemplate().save(customer);
    }

}

   在操作数据库时正常是要使用到事务管理器的

    <!-- hiberntae事务管理器,也需要将sessionFactory加进来,从hibernate中得代码就可以看出来,事务也是由sessionFactory获取来的-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

  4、Spring整合Struts2

    Struts2配置文件(struts.xml),Struts2作用是什么,Spring如何管理Struts2

     struts.xml:要配置Struts项目的一些全局的属性,用户请求和响应Action之间的对应关系,以及配置Action中可能用到的参数,以及处理结果的返回页面。

    方式一:Action由Struts2管理

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <!-- 
    Struts2的action由Spring来负责进行实例化
      只有设置此常量才会引发struts.objectFactory.spring.autowire = name 生效,
      让Action按照名称自动注入Service
  
--> <constant name="struts.objectFactory" value="spring"/> <package name="crm" extends="struts-default" namespace="/"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="customer_*" class="com.xxx.crm.web.action.CustomerAction" method="{1}"> <result name="saveUI">/jsp/customer/add.jsp</result> </action> </package> </struts>

    applicationContext.xml需要配置Service

    <bean id="customerService" class="com.xxx.crm.service.impl.CustomerServiceImpl">
        <property name="customerDao" ref="customerDao"/>
    </bean>

    使用代码:

    // 属性注入
    private CustomerService customerService;
    
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
    
    public String save() {
    System.out.println("CustomerAction中的save方法执行了");
    customerService.save(customer);
    return NONE;
    }

    

    方式二:Action由Spring管理,Hibernate的配置交由Spring管理

      struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>    
    <package name="bean" extends="struts-default" namespace="/">
        <action name="customer_*" class="customerAction" method="{1}"></action>
    </package>
</struts>

      applicationContext.xml部分内容:Action是多例

    <bean id="customerAction" class="com.xxx.ssh.web.action.CustomerAction" scope="prototype">
        <property name="customerService" ref="customerService"></property>
    </bean>
    
    <bean id="customerService" class="com.xxx.ssh.service.impl.CustomerServiceImpl">
        <property name="customerDao" ref="customerDao"></property>
    </bean>
    
    <bean id="customerDao" class="com.xxx.ssh.dao.impl.CustomerDaoImpl" scope="prototype">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>  

SSH图解

 总结:

  1、Spring可以管理Action、Service、Dao、Hibernate

  2、两端对象都交给Spring管理需要手动完成属性注入

原文地址:https://www.cnblogs.com/WarBlog/p/14768726.html