SSH 三大框架的整合

参考地址

SSH三大框架的整合思想

  1. web应用的三层为:

    1.1 web层,(struts2),Struts2框架用的最多的是action

    1.2 service层(spring),spring中用的最多的是IoC和AOP,把对象的创建交给Spring进行管理

    1.3 dao层(hibernate),hibernate则是用来操作数据库,进行CRUD

  2. 哪么这三个框架应该是如何整合呢?

    思想是两两整合:

    2.1 struts2和Spring进行整合

     2.1.1 在struts中action的创建交给Spring进行创建,但是要注意action是多实例的。
    
     2.1.2 要注意导入spring整合Struts2的jar包
    

    2.2 hibernate和Spring进行整合

     2.2.1 hibernate中的核心类是SessionFactory,这里要把SessionFactory的创建交给Spring进行管理
    
     2.2.2 Hibernate的核心文件中进行了数据库信息的配置,这里也要交给Spring进行处理
    
     2.2.3 为Dao对象配置持久层的Spring提供的Template
    
     2.2.4 注意导入Spring整合DAO层的ORM包
    

Struts2和Spring整合的具体步骤

  1. 把Struts2的action交给Spring进行管理

  2. 实现过程
    2.1 导入用于整合的jar包
    2.1.1 导入Spring单独使用需要的jar包


    2018-11-22_140128.png

    2.1.2 导入Struts2中所需的最少jar包,就是在Struts2项目解压之后的 apps中有一个blank项目,将其中的jar包导入进来即可


    2018-11-22_140224.png

    2.1.3 Spring为了整合Struts还需要额外再导入一个jar包


    2018-11-22_140304.png

3.创建Action

package com.action;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction1 extends ActionSupport {
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }
}

4.创建Strut2的核心配置文件,位置在src下面,名称是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 name="action" extends="struts-default" namespace="/">

        <action name="userAction" class="com.action.UserAction">

        </action>

    </package>

</struts>
  1. 在web.xml中配置struts2的过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>spring_struts2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

   <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>
</web-app>

至此,上面四步已经将Struts2的环境配置好了,然后就是来配置Spring了

  1. 导入Spring整合Web项目的jar包,也就是监控项目启动的监听器所在的jar包。

  2. 创建Spring的核心配置文件并在其中引入约束

    这个约束配置的比较多,可以直接拿过来使用的。
    (本人习惯命名为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:aop="http://www.springframework.org/schema/aop"
    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/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

</beans>
  1. 把action交给Spring进行配置
  1 <!-- 配置action的对象 -->
  2 <!-- 注意action是多实例的,因此我们这里把scope配置为prototype的 -->
  3 <bean id="userAction" class="com.action.UserAction" scope="prototype"></bean>

这里使用注解的方式替代以上代码即可, 在UserAction中加入@Component和@Scope("prototype")的注解,但是使用注解别忘了在Spring的核心配置文件中添加 扫描注解的配置

<!-- 配置 扫描 注解 ,自动 配置bean ,启动 @Autowired -->
<context:component-scan base-package="com"></context:component-scan>

但是如果Struts2和Spring像这样分别配置了Action的话,这样就不起作用了,这里的做法就是不在Struts2的配置文件struts.xml中写全路径,因为这样就不是从Spring中取出来的,这里将Struts2中Action的配置改为:

<?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 name="action" extends="struts-default" namespace="/">

        <action name="userAction" class="userAction">

        </action>

    </package>

</struts>

此处将class的值与bean的id的值保持一致


注意对应关系
  1. Spring监听器的配置(web.xml中配置)
<context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 这里如果applicationContext.xml在包com.ssh下,那么就应该写为:cn/ssh/bean.xml -->
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- 配置Spring的监听器 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  1. 测试准备

    10.1 所需的为Struts2的核心配置文件:struts.xml

    10.2 Spring的配置文件:bean.xml

    10.3 项目的配置文件:web.xml

    10.4 Struts2的UserAction类

    10.5 在UserAction中对UserService的调用

    10.6 UserService中对UserDao的调用

    10.7 UserDao类的编写

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 name="action" extends="struts-default" namespace="/">
        <action name="userAction" class="userAction">

        </action>
    </package>

</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ssh_intergration</display-name>
  <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>
    
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 这里如果application.xml在包cn.ssh下,那么就应该写为:cn/ssh/applicationContext.xml -->
    <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <!-- 配置Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>

UserDao.java

package com.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.pojo.User;

@Component
public class UserDao {

    public void add() {
    
        System.out.println("userDao add ......");
    }
}

UserService.java

package com.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dao.UserDao;

@Component
public class UserService {
    @Autowired
    private UserDao userDao;
    
    public void add() {
        userDao.add();
        System.out.println("UserService add .....");
    }
}

UserAction.java

package com.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.service.UserService;
//通过注解的方式  相当于 <bean id="userAction" class="com.ssh.domain.UserAction" scope="prototype"></bean> 配置action对象
@Component
//注意action是多实例的
@Scope("prototype")
public class UserAction extends ActionSupport {
    
    @Autowired
    private UserService userService;

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        userService.add();
        System.out.println("action add ....");
        return null;
    }
}

11.测试结果


2018-11-22_134401.png

Hibernate和Spring整合的具体步骤

这里也要解决两个问题:

  1. 把Hibernate中的核心配置文件中数据据库的配置交给Spring来管理

  2. 把Hibernate中SessionFactory的创建也是交给Spring来管理的

  3. 下面来看看具体的步骤:

    3.1 导入Hibernate的jar包


    最后是连接池的jar包
2018-11-22_140852.png
3.3 搭建Hibernate环境
    3.3.1 创建一个实体类:User.java
package com.pojo;


public class User {
    
    private int uid;

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private String username;

    private String password;
}

3.3.2 创建User.java的hibernate映射文件user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- DTD是约束,可以在核心包里面找 -->
<!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>
        <!-- 配置C3P0连接池 -->
        <!-- 注意这个类要配置进去 -->
        <property name="connection.provider_class">org.hibernate.c3p0.internal.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>

        <!-- 设置jdbc的隔离级别 -->
        <property name="hibernate.connection.isolation">4</property>

    </session-factory>
</hibernate-configuration>

3.3.3 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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 配置 扫描 注解 ,自动 配置bean ,启动 @Autowired -->
    <context:component-scan base-package="com"></context:component-scan>
    
    <!-- 把Hibernate中的核心配置文件中数据据库的配置交给Spring来管理  -->
    <!-- 配置数据源:方法一,使用C3P0方式(推荐) -->
    <!-- p:driverClass="com.mysql.jdbc.Driver"  p名称空间注入 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close" p:driverClass="com.mysql.jdbc.Driver"
        p:jdbcUrl="jdbc:mysql://localhost:3306/ssh" p:user="root" p:password="root" />
    <!-- hibernate 的sessionFactory交给spring进行配置  -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource">
        <property name="mappingLocations">
            <list>
                <value>classpath*:/com/*.hbm.xml</value>
            </list>
        </property>
        <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>
    </bean>
    
    <!-- 配置HibernateTemplate -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <!-- 注入sessionFactory -->
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <!-- 配置事务管理器 -->
    <!-- 注意这里用的是hibernate5 (特别注意使用的版本) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    </beans>

3.3.4 创建user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入Hibernate映射文件约束 -->
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.pojo.User" table="t_user">
        <id name="uid">
            <generator class="native"></generator>
        </id>
        <property name="username"></property>
        <property name="password"></property>
    </class>
</hibernate-mapping>

3.3.5 测试

UserDao

package com.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.pojo.User;

@Component
// 开启事务 ( 需要配置 )
@Transactional
public class UserDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;
    public void add() {
        User user = new User();
        user.setUsername("阿部多瑞");
        user.setPassword("666");
        
        hibernateTemplate.save(user);
        System.out.println("userDao add ......");
    }
}

这里HibernateTemplate是5的版本 测试之后再数据库中生成了表及数据代表成功

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354