【Spring MVC学习笔记 四】Spring-SpringMVC-MyBatis框架整合(下)

简介: 【Spring MVC学习笔记 四】Spring-SpringMVC-MyBatis框架整合(下)

6 spring-dao.xml整合配置编写

然后我们需要将MyBatis的相关配置整合到Spring中,所以SqlSession的创建及Mapper对象的创建都托管给了Spring:

spring-dao.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"
       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 ">
    <!-- 扫描dao相关的bean,Mapper对象自动扫描注入Spring-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包,扫描后依据接口自动创建Mapper对象 -->
        <property name="basePackage" value="com.example.ssm_frame.dao"/>
    </bean>
    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!-- 加载数据库配置信息 -->
    <context:property-placeholder location="classpath:properties/db.properties" system-properties-mode="NEVER"/>
    <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
</beans>

Spring框架实现

接下来我们实现下Spring框架,按照如下步骤。

1 数据传输类创建(DTO)

理论上DTO和PO不同,需要做转换,但是这里我们项目比较简单,所以还用之前的Person

2 PersonService接口创建

然后我们需要创建PersonService。

PersonService

package com.example.ssm_frame.service;
import com.example.ssm_frame.model.Person;
import java.util.List;
public interface PersonService {
    List<Person> getPersonList();
    int addAndSendPerson(Person person);
}

3 PersonServiceImpl实现类创建

依据PersonService实现PersonServiceImpl,这里我们使用自动装配调用Dao层自动生成的Mapper对象。

PersonServiceImpl

package com.example.ssm_frame.serviceImpl;
import com.example.ssm_frame.dao.PersonDao;
import com.example.ssm_frame.model.Person;
import com.example.ssm_frame.service.PersonService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class PersonServiceImpl implements PersonService {
    @Resource
    private PersonDao personDao;
    @Override
    public List<Person> getPersonList() {
        List<Person> personList=personDao.getPersonList();
        for (Person person : personList) {
            System.out.println(person);
        }
        return personList;
    }
    @Override
    @Transactional
    public int addAndSendPerson(Person person) {
        int result=personDao.addPerson(person);
        this.sendMessage(person);
        return result;
    }
    public void sendMessage(Person person){
        System.out.println("人员新增到下游系统失败"+person);
        throw new RuntimeException();
    }
}

4 日志监控AOP类创建

我们需要用AOP实现方法前后的记录:

LogAop

package com.example.ssm_frame.aop;
import java.time.LocalDateTime;
/**
 * * @Name LogProxy
 * * @Description
 * * @author tianmaolin
 * * @Data 2021/8/24
 */
public class LogAop {
    public void beforeLog()  {
        System.out.println("日志记录开始"+ LocalDateTime.now());
    }
    public void afterLog()  {
        System.out.println("日志记录结束"+ LocalDateTime.now().plusMinutes(5));
    }
}

5 applicationContext.xml核心配置编写

我们需要配置核心的启动配置文件,当然现在为空,最后我们再整合

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

6 spring-service.xml整合配置编写

然后我们配置下spring-service.xml来实现事务管理和日志管理

spring-service.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.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 http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
     <!-- 扫描service相关的bean,自动注入Spring-注解配置开启,该配置项其实也包含了自动注入功能,
     因此当使用<context:component-scan/>后,即可将<context:annotation-config/>省去 -->
    <context:component-scan base-package="com.example.ssm_frame.serviceImpl" />
    <!-- 配置事务管理器,开启事务的注解驱动-->
    <tx:annotation-driven />
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="myDataSource" />
    </bean>
    <!-- 配置日志管理器-->
    <bean id="logAop" class="com.example.ssm_frame.aop.LogAop"></bean>
    <!--aop的配置-日志记录-->
    <aop:config proxy-target-class="true">
        <aop:aspect ref="logAop">
            <!--切点-->
            <aop:pointcut id="logPointCut" expression="execution(* com.example.ssm_frame.service..*.*(..))"/>
            <!--切点-通知-->
            <aop:before pointcut-ref="logPointCut" method="beforeLog"/>
            <aop:after pointcut-ref="logPointCut" method="afterLog"/>
        </aop:aspect>
    </aop:config>
</beans>

SpringMVC框架实现

接下来我们开始配置SpringMVC框架以及整合配置文件。

1 视图对象类创建(VO)

理论上VO和PO不同,需要做转换,但是这里我们项目比较简单,所以还用之前的Person

2 控制器PersonController类创建

我们来配置中心控制器,并自动装配Service层的实现,调用方法获取结果传输到JSP页面。

PersonController

package com.example.ssm_frame.controller;
import com.example.ssm_frame.model.Person;
import com.example.ssm_frame.serviceImpl.PersonServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/person")
public class PersonController {
    @Resource
    private PersonServiceImpl personServiceImpl;
    @RequestMapping("getPersonList")
    public String requestDispatch(@RequestParam("username") String username, ModelMap modelMap) {
        if(username.equals("root")){
           List<Person> personList=personServiceImpl.getPersonList();
            modelMap.addAttribute("personList", personList);
        }
        return "list";
    }
}

注意SpringMVC默认的作用域时一次request,无论是Model还是ModelMap,放置的上下文作用域都是一次request。

3 视图页list.jsp创建

然后我们编写写列表信息:

list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page  pageEncoding="UTF-8" %>
<html>
<head>
    <title>人员列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>人员列表 —— 显示所有人员</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>用户名</th>
                    <th>年龄</th>
                    <th>手机号</th>
                    <th>邮箱</th>
                    <th>兴趣爱好</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="person" items="${requestScope.get('personList')}">
                    <tr>
                        <td>${person.getUsername()}</td>
                        <td>${person.getAge()}</td>
                        <td>${person.getPhone()}</td>
                        <td>${person.getEmail()}</td>
                        <td>${person.getHobby()}</td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>

4 web.xml配置注册DispatcherServlet

然后我们将中心控制器注册到web.xml,用来启动时读取:

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">
    <!--配置前端控制器-->
    <servlet>
        <!--1.注册DispatcherServlet-->
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--关联一个springMVC的配置文件:【servlet-name】-servlet.xml,注意,我们这里关联的是主入口的配置文件-->
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!--启动级别-1,在Tomcat启动时就初始化Spring容器-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--encodingFilter-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--Session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

5 springmvc-servlet.xml核心配置编写

springmvc-servlet.xml核心配置我们用spring-mvc.xml来替代。

6 spring-mvc.xml整合配置编写

MVC的核心配置即是springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 扫描controller相关的bean,自动注入Spring-->
    <context:component-scan base-package="com.example.ssm_frame.controller"/>
    <!-- 让Spring MVC不处理静态资源 -->
    <mvc:default-servlet-handler />
    <!--支持mvc注解驱动-->
    <mvc:annotation-driven />
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

SSM框架整合

三个框架的主体都编写完毕后,我们来整合框架并做测试

1 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="spring-configs/spring-dao.xml"/>
    <import resource="spring-configs/spring-service.xml"/>
    <import resource="spring-configs/spring-mvc.xml"/>
</beans>

2 配置Tomcat服务器

然后我们配置Tomcat服务器:

3 启动服务器并进行测试

最后我们在浏览器请求访问然后看展示的效果:

同时通过日志我们从后台也能看到执行过程:

总结一下

这样就整合完成了SSM框架用来实现了一个简单的需求,事实上无论是早年间的Servlet+JSP+JDBC或是后来的SSH框架直至今天的SSM框架,其完成的功能都是固定的,例如JDBC、Hibernate和MyBatis完成的工作是数据持久化,它们都需要处理数据缓存、连接池、结果集映射、查询参数绑定等问题,但随着技术的发展,实现的成本越来越低;Servlet、Struts和SpringMVC都充当了(中心)控制器的功能,它们都需要处理事务、文件上传下载、请求转发、重定向、过滤器、监听器等问题,同样随着技术的发展,实现的成本越来越低;Spring呢作为后来的整合老大哥,通过IOC技术接管了各种类和各种框架,让所有的框架从大杂烩成为了一体,更好的服务于开发者。技术从来就是用来解决业务问题的,哪种实现方式更简单,我们用哪种,但不仅要知道怎么用还要知道为什么用,这才是重点。

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
相关文章
|
安全 Java Ruby
我尝试了所有后端框架 — — 这就是为什么只有 Spring Boot 幸存下来
作者回顾后端开发历程,指出多数框架在生产环境中难堪重负。相比之下,Spring Boot凭借内置安全、稳定扩展、完善生态和企业级支持,成为构建高可用系统的首选,真正经受住了时间与规模的考验。
927 2
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
1121 8
|
监控 Kubernetes Cloud Native
Spring Batch 批处理框架技术详解与实践指南
本文档全面介绍 Spring Batch 批处理框架的核心架构、关键组件和实际应用场景。作为 Spring 生态系统中专门处理大规模数据批处理的框架,Spring Batch 为企业级批处理作业提供了可靠的解决方案。本文将深入探讨其作业流程、组件模型、错误处理机制、性能优化策略以及与现代云原生环境的集成方式,帮助开发者构建高效、稳定的批处理系统。
1104 1
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1689 0
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1719 0
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
716 0
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
1407 0