eclipse环境下基于已构建struts2项目整合spring+hibernate

本文是基于已构建的struts2项目基础上整合

spring+hibernate,若读者还不熟悉struts2项目,请先阅读

eclipse环境下基于tomcat-7.0.82构建struts2项目

实现步骤:

第一步:引入spring所需jar包,如下图所示:

第二步:导入hibernate所需jar包,如下图中被选中jar文件:

第三步:导入struts-spring整合包,暂且就这么称呼吧

第四步:导入MySQL驱动包:

第五步:所有准备工作就绪后,接下来创建spring与hibernate配置文件,命名为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:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task  
http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

</beans>

   这是spring配置文件命名空间的引入,命名空间具体含义请参考前辈资料 

6.2.3 Spring 2.5配置文件详解(1)

第六步:在web.xml文件中配置对spring的监听,配置如下所示:

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSHDemo</display-name>
  
      <!-- spring的监听器配置开始 -->
    <!-- spring监听器的作用:提供实例(IOC) -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  
  <!-- 将请求路径交由struts过滤 -->
  <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的监听。

第七步:项目下构建业务层接口(TestServiceI)、实现类(TestServiceImpl)以及数据库操作层接口(TestDaoI)、实现类(TestDaoImpl)

整个项目结构如下图所示:

其中dao层实现类中我们需要注入一个session工厂(工厂注入请留意本文后续),接着打开session工厂用于操作数据库,代码如下所示:

package wjt.com.test.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import wjt.com.test.dao.TestDaoI;

public class TestDaoImpl implements TestDaoI{
    
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    private Session getCurrentSession() {
        try {
            return sessionFactory.getCurrentSession();
        } catch (HibernateException e) {
            return sessionFactory.openSession();
        }
    }

    @Override
    public void testDaoMethod() {
        System.out.println("dao层测试方法...");
        if(getCurrentSession()!=null) {
            System.out.println("session工厂注入成功!");
        }
        
    }
    
    

}

其中service层实现类中我们暂时写一个空方法进行测试dao层接口对象的注入成功与否并调用dao层方法,代码如下:

package wjt.com.test.service.impl;

import wjt.com.test.dao.TestDaoI;
import wjt.com.test.service.TestServiceI;

public class TestServiceImpl implements TestServiceI{
    
    private TestDaoI testDao;
    
    public void setTestDao(TestDaoI testDao) {
        this.testDao = testDao;
    }



    @Override
    public void testServiceMethod() {
        System.out.println("service层测试方法...");
        testDao.testDaoMethod();
    }

}

其中Action层我们在原来struts2项目的基础上注入service层接口并调用其方法,代码如下:

package wjt.com.test.action;

import com.opensymphony.xwork2.ActionSupport;

import wjt.com.test.service.TestServiceI;

public class TestAction extends ActionSupport{
    
    private TestServiceI testService;
    
    public void setTestService(TestServiceI testService) {
        this.testService = testService;
    }



    public String execute() throws Exception {
        System.out.println("struts==========================");
        testService.testServiceMethod();
        return "success";
    }
}

整个s2sh项目中的结构布局如上述第七步所示,用于视图映射的类我们封装在action包下,用于实现业务逻辑的我们封装在service包下,用于访问数据库对数据进行操作的我们封装在dao包下。

第八步:配置spring+hibernate的配置文件

截止到现在整个s2sh项目的准备工作已经准备完毕,接下来我们我们配置hibernate的数据源、session工厂,配置spring的核心之一控制反转IOC或称为依赖注入DI。

配置如下:

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

    <!-- 数据源配置 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/wjt_test?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;autoReconnect=true" />
        <property name="username" value="root" />
        <property name="password" value="wujingtao" />
    </bean>

    <!-- 配置hibernate session工厂 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>

    </bean>
    
    <!-- 注入对象  采用属性注入方式-->
    
    <bean id="testDao" class="wjt.com.test.dao.impl.TestDaoImpl" scope="prototype">
        <property name="sessionFactory" ref="sessionFactory"/><!-- 引用上方的hibernate工厂 -->
    </bean>
    
    <bean id="testService" class="wjt.com.test.service.impl.TestServiceImpl" scope="prototype">
        <property name="testDao" ref="testDao"/>
    </bean>
    
    <bean id="testAction" class="wjt.com.test.action.TestAction" scope="prototype">
        <property name="testService" ref="testService"/>
    </bean>


</beans>

其中IOC配置采用属性注入的方式,大家可以根据个人喜好选择spring注入的几种方式,我个人偏爱基于注解的属性注入方式,注解方式注入会在后续的文章中给出。

第九步:将struts2运行时的对象交由spring创建,即所谓的应用IOC

在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"><!-- 这里要和struts2版本号统一 -->

<struts>

    <!-- 告知Struts2运行时使用Spring来创建对象 这行代码是新加的-->
    <constant name="struts.objectFactory" value="spring" />

    <package name="default" extends="struts-default">
        <action name="login" class="wjt.com.test.action.TestAction">
            <result name="success">index.jsp</result>
        </action>
    </package>

</struts>

测试项目:

在tomcat下部署并启动项目

浏览器地址栏输入:http://localhost:8080/SSHDemo/login

浏览器显示如下所示:

eclipse输出显示如下:(因为我们在各层有打印信息)

到这里完整的s2sh项目构建完毕并通过测试。

本人是刚毕业的小白,写文章的目的是全当给自己做笔记了,博文有不合理的地方还请读者指出!

 

posted @ 2017-11-29 23:10  Mr至简  阅读(1039)  评论(1编辑  收藏  举报