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

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: 【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技术接管了各种类和各种框架,让所有的框架从大杂烩成为了一体,更好的服务于开发者。技术从来就是用来解决业务问题的,哪种实现方式更简单,我们用哪种,但不仅要知道怎么用还要知道为什么用,这才是重点。

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
打赏
0
0
0
0
33
分享
相关文章
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
85 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
微服务——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`
65 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
105 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
77 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = &quot;/test&quot;, produces = &quot;application/json; charset=UTF-8&quot;)`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
85 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
63 0
DDD四层架构和MVC三层架构的个人理解和学习笔记
领域驱动设计(DDD)是一种以业务为核心的设计方法,与传统MVC架构不同,DDD将业务逻辑拆分为应用层和领域层,更关注业务领域而非数据库设计。其四层架构包括:Interface(接口层)、Application(应用层)、Domain(领域层)和Infrastructure(基础层)。各层职责分明,避免跨层调用,确保业务逻辑清晰。代码实现中,通过DTO、Entity、DO等对象的转换,结合ProtoBuf协议,完成请求与响应的处理流程。为提高复用性,实际项目中可增加Common层存放公共依赖。DDD强调从业务出发设计软件,适应复杂业务场景,是微服务架构的重要设计思想。
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
188 29
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
45 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
118 0