Spring Boot 2.X(三):使用 Spring MVC + MyBatis + Thymeleaf 开发 web 应用

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 前言Spring MVC 是构建在 Servlet API 上的原生框架,并从一开始就包含在 Spring 框架中。本文主要通过简述 Spring MVC 的架构及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架来简单快速构建一个 Web 项目。

前言


Spring MVC 是构建在 Servlet API 上的原生框架,并从一开始就包含在 Spring 框架中。本文主要通过简述 Spring MVC 的架构及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架来简单快速构建一个 Web 项目。

Web MVC 架构及分析


MVC 三层架构如图所示,红色字体代表核心模块。其中 MVC 各分层分别为:

  • Model (模型层)处理核心业务(数据)逻辑,模型对象负责在数据库中存取数据。这里的“数据”不仅限于数据本身,还包括处理数据的逻辑。
  • View(视图层)用于展示数据,通常数据依据模型数据创建。
  • Controller(控制器层)用于处理用户输入请求和响应输出,从试图读取数据,控制用户输入,并向模型发送数据。Controller 是在 Model 和 View 之间双向传递数据的中间协调者。

Spring MVC 架构及分析


Spring MVC 处理一个 HTTP 请求的流程,如图所示:

整个过程详细介绍:
1.用户发送请求至前端控制器 DispatcherServlet。
2.DispatcherServlet 收到请求调用处理器映射器 HandlerMapping。
3.处理器映射器根据请求 URL 找到具体的 Controller 处理器返回给 DispatcherServlet。
4.DispatcherServlet 通过处理器适配器 HandlerAdapter 调用 Controller 处理请求。
5.执行 Controller 处理器的方法。
6.Controller 执行完成返回 ModelAndView。
7.HandlerAdapter 将 Controller 执行结果 ModelAndView 返回给 DispatcherServlet。
8.DispatcherServlet 将 ModelAndView 的 ViewName 传给视图解析器 ViewReslover。
9.ViewReslover 解析后返回具体的视图 View。
10.DispatcherServlet 传递 Model 数据给 View,对 View 进行渲染(即将模型数据填充至视图中)。
11-12.DispatcherServlet 响应用户。

Spring Boot + Spring MVC + MyBatis + Thymeleaf


本段我们主要通过构建项目,实现一个分页查询。

1.项目构建

项目结构如图所示:

1.1 pom 引入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.zwqh</groupId>
    <artifactId>spring-boot-ssm-thymeleaf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-ssm-thymeleaf</name>
    <description>spring-boot-ssm-thymeleaf</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- 热部署模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
        </dependency>


        <!-- mysql 数据库驱动. -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- mybaits -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <!-- pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.12</version>
        </dependency>

        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
1.2 WebMvcConfig 配置
package cn.zwqh.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;


@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
   

    /**
     * 静态资源配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");//静态资源路径 css,js,img等
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");//视图
        registry.addResourceHandler("/mapper/**").addResourceLocations("classpath:/mapper/");//mapper.xml
        super.addResourceHandlers(registry);

    }

    /**
     * 视图控制器配置
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       
        registry.addViewController("/").setViewName("/index");//设置默认跳转视图为 /index
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);


    }
    /**
     * 视图解析器配置  控制controller String返回的页面    视图跳转控制 
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
   
       // registry.viewResolver(new InternalResourceViewResolver("/jsp/", ".jsp"));
        super.configureViewResolvers(registry);
    }

}
1.3 application.properties 配置
#thymeleaf
spring.thymeleaf.cache=false
#datasource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#mybatis
mybatis.mapper-locations=classpath:/mapper/*.xml
#logging
logging.path=/user/local/log
logging.level.cn.zwqh=debug
logging.level.org.springframework.web=info
logging.level.org.mybatis=error
1.4 Controller
@Controller
@RequestMapping("/user")
public class UserController {
   

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public ModelAndView showUserList(int pageNum, int pageSize) {
   
        PageInfo<UserEntity> pageInfo = userService.getUserList(pageNum, pageSize);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("pageInfo",pageInfo);
        return modelAndView;
    }
}
1.5 Service 及 ServiceImpl

UserService

public interface UserService {
   

    PageInfo<UserEntity> getUserList(int pageNum, int pageSize);

}

UserServiceImpl

@Service
public class UserServiceImpl implements UserService{
   

    @Autowired
    private UserDao userDao;

    @Override
    public PageInfo<UserEntity> getUserList(int pageNum, int pageSize) {
   
        PageHelper.startPage(pageNum, pageSize);
        List<UserEntity> list=userDao.getAll();
        PageInfo<UserEntity> pageData= new PageInfo<UserEntity>(list);
        System.out.println("当前页:"+pageData.getPageNum());
        System.out.println("页面大小:"+pageData.getPageSize());
        System.out.println("总数:"+pageData.getTotal());    
        System.out.println("总页数:"+pageData.getPages());    
        return pageData;
    }
}
1.6 Dao
public interface UserDao {
   
    /**
     * 获取所有用户
     * @return
     */
    List<UserEntity> getAll();

}

记得在启动类里加上@MapperScan

@SpringBootApplication
@MapperScan("cn.zwqh.springboot.dao")
public class SpringBootSsmThymeleafApplication {
   

    public static void main(String[] args) {
   
        SpringApplication.run(SpringBootSsmThymeleafApplication.class, args);
    }

}
1.7 Mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.zwqh.springboot.dao.UserDao">
    <resultMap type="cn.zwqh.springboot.model.UserEntity" id="user">
        <id property="id" column="id"/>
        <result property="userName" column="user_name"/>
        <result property="userSex" column="user_sex"/>
    </resultMap>
    <!-- 获取所有用户 -->
    <select id="getAll" resultMap="user">
        select * from t_user
    </select>
</mapper>
1.8 实体 UserEntity
public class UserEntity {
   

    private Long id;
    private String userName;
    private String userSex;
    public Long getId() {
   
        return id;
    }
    public void setId(Long id) {
   
        this.id = id;
    }
    public String getUserName() {
   
        return userName;
    }
    public void setUserName(String userName) {
   
        this.userName = userName;
    }
    public String getUserSex() {
   
        return userSex;
    }
    public void setUserSex(String userSex) {
   
        this.userSex = userSex;
    }

}
1.9 html 页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>Thymeleaf是一个用于Web和独立环境的现代服务器端Java模板引擎。SpringBoot推荐使用Thymeleaf。</p>
<p>下面是表格示例:</p>
<table border="1">
    <thead>
        <tr>
            <th width="100">ID</th>
            <th width="100">姓名</th>
            <th width="100">性别</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="user:${pageInfo.list}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.userName}"></td>
            <td th:text="${user.userSex}"></td>
        </tr>
    </tbody>
</table>
<p>
<a th:href="${
    '/user/list?pageNum='+(pageInfo.pageNum-1>=1?pageInfo.pageNum-1:1)+'&pageSize=10'}">上一页</a>

<a th:href="${
    '/user/list?pageNum='+(pageInfo.pageNum+1<=pageInfo.pages?pageInfo.pageNum+1:pageInfo.pages)+'&pageSize=10'}">下一页</a>    
总数:<span th:text="${pageInfo.total}"></span>
</p>
</body>
</html>

测试

通过浏览器访问:http://127.0.0.1:8080/user/list?pageNum=1&pageSize=10 进行测试。效果如图:

示例代码

github

码云

非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.

原文标题: Spring Boot 2.X(三):使用 Spring MVC + MyBatis + Thymeleaf 开发 web 应用

如果文章对您有帮助,请扫码关注下我的公众号,文章持续更新中...

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
6天前
|
前端开发 Java 测试技术
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
30 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
|
6天前
|
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`
28 0
|
6天前
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
32 0
|
6天前
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
37 0
|
6天前
|
前端开发 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
24 0
|
6天前
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 的使用
本文介绍了 Thymeleaf 在 Spring Boot 项目中的使用方法,包括访问静态页面、处理对象和 List 数据、常用标签操作等内容。通过示例代码展示了如何配置 404 和 500 错误页面,以及如何在模板中渲染对象属性和列表数据。同时总结了常用的 Thymeleaf 标签,如 `th:value`、`th:if`、`th:each` 等,并提供了官方文档链接以供进一步学习。
48 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 的使用
|
6天前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
18 0
|
6天前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
37 0
|
6天前
|
缓存 Java 应用服务中间件
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——依赖导入和Thymeleaf相关配置
在Spring Boot中使用Thymeleaf模板,需引入依赖`spring-boot-starter-thymeleaf`,并在HTML页面标签中声明`xmlns:th=&quot;http://www.thymeleaf.org&quot;`。此外,Thymeleaf默认开启页面缓存,开发时建议关闭缓存以实时查看更新效果,配置方式为`spring.thymeleaf.cache: false`。这可避免因缓存导致页面未及时刷新的问题。
26 0
|
Web App开发 存储 Java
Spring Web应用的最大瑕疵
Spring Web应用的最大瑕疵 众所周知, 现在的Spring框架已经成为构建企业级Java应用事实上的标准了,众多的企业项目都构建在Spring项目及其子项目之上,特别是Java Web项目,很多都使用了Spring并且遵循着Web、Service、Dao这样的分层原则,下层向上层提供服务;不过Petri Kainulainen在其博客中却指出了众多Spring Web应用的最大瑕疵,请继续阅读看看文中所提到的问题是否也出现在你的项目当中。
879 0

热门文章

最新文章