Spring4 - Hibernate4 - Struts2 集成

一、集成步骤

1、新建一个web项目

2、导入Hibernate4.3.5需要的jar包

Hibernate4.3.5Requiredjar包.png

3、数据库包

  • druid-1.0.15.jar
  • mysql-connector-java-8.0.16.jar

4、Spring需要的依赖包

  • spring-aop-4.1.2.RELEASE.jar
  • spring-aspects-4.1.2.RELEASE.jar
  • spring-beans-4.1.2.RELEASE.jar
  • spring-context-4.1.2.RELEASE.jar
  • spring-core-4.1.2.RELEASE.jar
  • spring-expression-4.1.2.RELEASE.jar
  • spring-jdbc-4.1.2.RELEASE.jar
  • spring-orm-4.1.2.RELEASE.jar
  • spring-test-4.1.2.RELEASE.jar
  • spring-tx-4.1.2.RELEASE.jar

5、db.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=admin
jdbc.url=jdbc:mysql:///springdemo?useSSL=true&serverTimezone=UTC
jdbc.maxActive=5
#jdbc.url=jdbc:mysql:///springdemo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

6、domain

package com.revanwang.ssh.domain;


import lombok.Data;

@Data
public class Employee {
    private Long        id;
    private String      name;
    private Integer     age;
}

7、dao

package com.revanwang.ssh.dao.impl;

import com.revanwang.ssh.dao.IEmployeeDAO;
import com.revanwang.ssh.domain.Employee;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.List;

public class EmployeeDAOImpl implements IEmployeeDAO {

    private SessionFactory sessionFactory;


    public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory;
    }

    @Override
    public void save(Employee employee) {
        Session session = this.sessionFactory.getCurrentSession();
        session.save(employee);
    }

    @Override
    public void update(Employee employee) {
        Session session = this.sessionFactory.getCurrentSession();
        session.update(employee);
    }

    @Override
    public void delete(Employee employee) {
        Session session = this.sessionFactory.getCurrentSession();
        session.delete(employee);
    }

    @Override
    public Employee get(Long id) {
        Session session = this.sessionFactory.getCurrentSession();
        return (Employee) session.get(Employee.class, id);
    }

    @Override
    public List<Employee> getList() {
        Session session = this.sessionFactory.getCurrentSession();
        Query query = session.createQuery("SELECT e FROM Employee e");
        return query.list();
    }
}

7、service

package com.revanwang.ssh.service.impl;

import com.revanwang.ssh.dao.IEmployeeDAO;
import com.revanwang.ssh.domain.Employee;
import com.revanwang.ssh.service.IEmployeeService;
import lombok.Setter;

import java.util.List;

public class EmployeeServiceImpl implements IEmployeeService {

    @Setter
    private IEmployeeDAO employeeDAO;

    @Override
    public void save(Employee employee) {
        this.employeeDAO.save(employee);
    }

    @Override
    public void update(Employee employee) {
        this.employeeDAO.update(employee);
    }

    @Override
    public void delete(Employee employee) {
        this.employeeDAO.delete(employee);
    }

    @Override
    public Employee get(Long id) {
        return this.employeeDAO.get(id);
    }

    @Override
    public List<Employee> getList() {
        return this.employeeDAO.getList();
    }
}

8、test

package com.revanwang.ssh.test;

import com.revanwang.ssh.domain.Employee;
import com.revanwang.ssh.service.IEmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class EmployeeServiceTest {

    @Autowired
    private IEmployeeService employeeService;

    @Test
    public void save() {
        Employee employee = new Employee();
        employee.setName("阿朱");
        employee.setAge(20);
        employeeService.save(employee);
    }

    @Test
    public void update() {
        Employee employee = new Employee();
        employee.setId(8L);
        employee.setName("阿朱");
        employeeService.update(employee);
    }

    @Test
    public void delete() {
        Employee employee = new Employee();
        employee.setId(3L);
        employeeService.delete(employee);
    }

    @Test
    public void get() {
        System.out.println(employeeService.get(1L));
    }

    @Test
    public void getList() {
        List<Employee> list = employeeService.getList();
        for (Employee emp : list) {
            System.out.println(emp);
        }
    }
}

二、Struts2集成

1、导入jar包

Struts2.png

注意:因为Hibernate中也依赖javassist.jar包,Struts2也依赖javassist.jar包,所以只需要导入一个javassist.jar包就好

2、web.xml配置

2.1 前端控制器

    <!--前端控制器-->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

2.2 系统启动,初始化Spring容器

<!--系统启动,就初始化Spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

2.3 监听器寻找Spring的配置文件

    <!--告诉监听器去哪里去找Spring的配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--告诉监听器去哪里去找Spring的配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--系统启动,就初始化Spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--前端控制器-->
    <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>

</web-app>

三、Struts2的Action创建权转交给Spring管理

  • applicationContext.xml

    <!--  5、配置Action  -->
    <bean id="employeeAction" class="com.revanwang.ssh.web.action.EmployeeAction" scope="prototype">
        <property name="employeeService" ref="employeeService"/>
    </bean>
  • 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="employeePKG" namespace="/" extends="struts-default">
        <action name="employee" class="employeeAction"/>
    </package>

</struts>

四、Spring和Struts2集成的原理

1、struts-default.xml文件

默认情况下,Struts2中所有的对象都是由 xWork 容器中的 ObjectFactory 创建的

<bean class="com.opensymphony.xwork2.ObjectFactory" name="struts"/>

2、struts2-spring-plugin.jar

struts2-spring-plugin.jar 是Spring和Struts2集成的桥梁。本身也是Struts2提供的一个插件,用来和Spring做整合。

<?xml version="1.0" encoding="UTF-8" ?>
<!--
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
-->
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
    
<struts>
    <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
    
    <!--  Make the Spring object factory the automatic default -->
    <constant name="struts.objectFactory" value="spring" />

    <constant name="struts.class.reloading.watchList" value="" />
    <constant name="struts.class.reloading.acceptClasses" value="" />
    <constant name="struts.class.reloading.reloadConfig" value="false" />

    <constant name="struts.disallowProxyMemberAccess" value="true" />
    <constant name="struts.json.result.excludeProxyProperties" value="true" />

    <package name="spring-default">
        <interceptors>
            <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
        </interceptors>
    </package>    
</struts>

重新定义了一个对象工厂,起名为spring。该对象工厂的类型是StrutsSpringObjectFactory,其本身就是Struts2的对象工厂。ObjectFactory的子类。用来设置:Struts2中所有的对象都由Spring来创建

五、Spring - Struts2 - Hibernate4 整合配置

  • 数据库配置文件(db.properties)

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=admin
jdbc.url=jdbc:mysql:///springdemo?useSSL=true&serverTimezone=UTC
jdbc.maxActive=5
#jdbc.url=jdbc:mysql:///springdemo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
  • applicationContext.xml

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


    <!--
        默认情况下,struts2中所有的对象都是由xWork容器中的ObjectFactory创建的
    -->
<!--    <bean class="com.opensymphony.xwork2.ObjectFactory" name="struts"/>-->

    <!--  5、配置Action  -->
    <bean id="employeeAction" class="com.revanwang.ssh.web.action.EmployeeAction" scope="prototype">
        <property name="employeeService" ref="employeeService"/>
    </bean>

    <!--  4、service  -->
    <bean id="employeeService" class="com.revanwang.ssh.service.impl.EmployeeServiceImpl">
        <property name="employeeDAO" ref="employeeDAO"/>
    </bean>

    <!--  3、employeeDAO  -->
    <bean id="employeeDAO" class="com.revanwang.ssh.dao.impl.EmployeeDAOImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!--  2、sessionFactory  -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 2.1管理数据库链接 -->
        <property name="dataSource" ref="dataSource_db"/>

        <!-- 2.2设置Hibernate -->
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
                hibernate.show_sql=true
                hibernate.format_sql=true
                hibernate.hbm2ddl.auto=update
            </value>
        </property>

        <!-- 2.3设置 bean.hbm.xml -->
        <property name="mappingLocations" value="classpath:com/revanwang/ssh/domain/*.hbm.xml"/>

    </bean>

    <!--  1、配置数据库  -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--  配置dataSource  -->
    <bean id="dataSource_db" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
    </bean>


    <!--  0、配置事务  -->
    <!--  what:增强事务  -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!--  when:什么时候  -->
    <tx:advice id="adviceId" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="list*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--  where:在哪里增加事务  -->
    <aop:config>
        <aop:pointcut id="pointcutId"
                      expression="execution(* com.revanwang.ssh.service.*Service.*(..))"/>
        <aop:advisor advice-ref="adviceId" pointcut-ref="pointcutId"/>
    </aop:config>

</beans>
  • 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="employeePKG" namespace="/" extends="struts-default">
        <action name="employee" class="employeeAction"/>
    </package>

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

推荐阅读更多精彩内容