Spring Boot整合Thymeleaf完整Web案例


Thymeleaf 是一种模板语言。那模板语言或模板引擎是什么?常见的模板语言都包含以下几个概念:数据(Data)、模板(Template)、模板引擎(Template Engine)和结果文档(Result Documents)。

  • 数据 数据是信息的表现形式和载体,可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。
  • 模板 模板,是一个蓝图,即一个与类型无关的类。编译器在使用模板时,会根据模板实参对模板进行实例化,得到一个与类型相关的类。
  • 模板引擎 模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。
  • 结果文档 一种特定格式的文档,比如用于网站的模板引擎就会生成一个标准的HTML文档。

模板语言用途广泛,常见的用途如下:

  • 页面渲染
  • 文档生成
  • 代码生成
  • 所有 “数据+模板=文本” 的应用场景

这里案例用途自然是 页面渲染,下面在 Spring Boot 中整合 Thymeleaf 实现完整 Web 案例。

一、运行 chapter-2-spring-boot-quick-start

chapter-2-spring-boot-quick-start 工程用的是内存式数据库,不需要配置数据源。下载运行即可。

1. 下载工程

git clone 下载工程 springboot-learning-example ,项目地址见 GitHub:

https://github.com/JeffLi1993/springboot-learning-example,即:

 
   
  1. git clone https://github.com/JeffLi1993/springboot-learning-example.git 

2. 工程结构

用 IDEA 打开工程,可以看到子工程 chapter-2-spring-boot-quick-start ,其目录如下:

 
   
  1. ├── pom.xml 
  2.  
  3. └── src 
  4.  
  5.    ├── main 
  6.  
  7.    │   ├── java 
  8.  
  9.    │   │   └── spring 
  10.  
  11.    │   │       └── boot 
  12.  
  13.    │   │           └── core 
  14.  
  15.    │   │               ├── QuickStartApplication.java 
  16.  
  17.    │   │               ├── domain 
  18.  
  19.    │   │               │   ├── User.java 
  20.  
  21.    │   │               │   └── UserRepository.java 
  22.  
  23.    │   │               ├── service 
  24.  
  25.    │   │               │   ├── UserService.java 
  26.  
  27.    │   │               │   └── impl 
  28.  
  29.    │   │               │       └── UserServiceImpl.java 
  30.  
  31.    │   │               └── web 
  32.  
  33.    │   │                   └── UserController.java 
  34.  
  35.    │   └── resources 
  36.  
  37.    │       ├── application.properties 
  38.  
  39.    │       ├── static 
  40.  
  41.    │       │   ├── css 
  42.  
  43.    │       │   │   └── default.css 
  44.  
  45.    │       │   └── images 
  46.  
  47.    │       │       └── favicon.ico 
  48.  
  49.    │       └── templates 
  50.  
  51.    │           ├── userForm.html 
  52.  
  53.    │           └── userList.html 
  54.  
  55.    └── test 
  56.  
  57.        └── java 
  58.  
  59.            └── spring 
  60.  
  61.                └── boot 
  62.  
  63.                    └── core 
  64.  
  65.                        ├── QuickStartApplicationTests.java 
  66.  
  67.                        └── domain 
  68.  
  69.                            └── UserRepositoryTests.java 

对应目录:

  • org.spring.springboot.controller - Controller 层
  • org.spring.springboot.dao - 数据操作层 DAO
  • org.spring.springboot.domain - 实体类
  • org.spring.springboot.service - 业务逻辑层
  • Application - 应用启动类
  • application.properties - 应用配置文件

模板是会用到下面两个目录

  • static 目录是存放 CSS、JS 等资源文件
  • templates 目录是存放视图

3. 编译运行工程

在该工程根目录,运行 maven 指令进行编译:

 
   
  1. cd chapter-2-spring-boot-quick-start  
  2. mvn clean install 

编译工程成功后,右键运行名为 QuickStartApplication.java 应用启动类的 main 函数,然后浏览器访问 localhost:8080/users 即可: 用户列表页面:


用户编辑页面:

二、详解 chapter-2-spring-boot-quick-start

工程代码:

1. pom.xml Thymeleaf 依赖

使用模板引擎,就在 pom.xml 加入 Thymeleaf 组件依赖:

 
   
  1. <!-- 模板引擎 Thymeleaf 依赖 -->  
  2. <dependency> 
  3.    <groupId>org.springframework.boot</groupId> 
  4.    <artifactId>spring-boot-starter-thymeleaf</artifactId> 
  5. </dependency> 

Thymeleaf 是什么? Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 后推荐使用。

整体个 pom.xml 配置如下:

 
   
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3.         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
  4.    <modelVersion>4.0.0</modelVersion> 
  5.  
  6.    <groupId>spring.boot.core</groupId> 
  7.    <artifactId>chapter-2-spring-boot-quick-start</artifactId> 
  8.    <version>0.0.1-SNAPSHOT</version> 
  9.    <packaging>jar</packaging> 
  10.    <name>chapter-2-spring-boot-quick-start</name
  11.    <description>第二章快速入门案例</description> 
  12.  
  13.    <parent> 
  14.        <groupId>org.springframework.boot</groupId> 
  15.        <artifactId>spring-boot-starter-parent</artifactId> 
  16.        <version>1.5.7.RELEASE</version> 
  17.    </parent> 
  18.  
  19.    <properties> 
  20.        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
  21.        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
  22.        <java.version>1.8</java.version>
  23.    </properties> 
  24.  
  25.    <dependencies> 
  26.  
  27.        <!-- Web 依赖 --> 
  28.        <dependency> 
  29.            <groupId>org.springframework.boot</groupId> 
  30.            <artifactId>spring-boot-starter-web</artifactId> 
  31.        </dependency> 
  32.  
  33.        <!-- 单元测试依赖 --> 
  34.        <dependency> 
  35.            <groupId>org.springframework.boot</groupId> 
  36.            <artifactId>spring-boot-starter-test</artifactId> 
  37.            <scope>test</scope> 
  38.        </dependency> 
  39.  
  40.        <!-- Spring Data JPA 依赖 :: 数据持久层框架 --> 
  41.        <dependency> 
  42.            <groupId>org.springframework.boot</groupId> 
  43.            <artifactId>spring-boot-starter-data-jpa</artifactId> 
  44.        </dependency> 
  45.  
  46.        <!-- h2 数据源连接驱动 --> 
  47.        <dependency> 
  48.            <groupId>com.h2database</groupId> 
  49.            <artifactId>h2</artifactId> 
  50.            <scope>runtime</scope> 
  51.        </dependency> 
  52.  
  53.        <!-- 模板引擎 Thymeleaf 依赖 --> 
  54.        <dependency> 
  55.            <groupId>org.springframework.boot</groupId> 
  56.            <artifactId>spring-boot-starter-thymeleaf</artifactId> 
  57.        </dependency> 
  58.    </dependencies> 
  59.  
  60.    <build> 
  61.        <plugins> 
  62.            <!-- Spring Boot Maven 插件 --> 
  63.            <plugin> 
  64.                <groupId>org.springframework.boot</groupId> 
  65.                <artifactId>spring-boot-maven-plugin</artifactId> 
  66.            </plugin> 
  67.        </plugins> 
  68.    </build> 
  69.  
  70. </project> 

2. Thymeleaf 依赖配置

在 Spring Boot 项目中加入 Thymeleaf 依赖,即可启动其默认配置。如果想要自定义配置,可以在 application.properties 配置如下:

 
   
  1. spring.thymeleaf.cache=true # Enable template caching. 
  2. spring.thymeleaf.check-template=true # Check that the template exists before rendering it. 
  3. spring.thymeleaf.check-template-location=true # Check that the templates location exists. 
  4. spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks. 
  5. spring.thymeleaf.encoding=UTF-8 # Template files encoding. 
  6. spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution. 
  7. spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers. 
  8. spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL. 
  9. spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes. 
  10. spring.thymeleaf.reactive.media-types= # Media types supported by the view technology. 
  11. spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses. 
  12. spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL. 
  13. spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. 
  14. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved. 

3. Thymeleaf 使用

Controller 如何将 View 指向 Thymeleaf

用户控制层代码如下:

 
   
  1. @Controller 
  2. @RequestMapping(value = "/users")     // 通过这里配置使下面的映射都在 /users 
  3. public class UserController { 
  4.  
  5.    @Autowired 
  6.    UserService userService;          // 用户服务层 
  7.  
  8.    /**
  9.     *  获取用户列表 
  10.     *    处理 "/users" 的 GET 请求,用来获取用户列表 
  11.     *    通过 @RequestParam 传递参数,进一步实现条件查询或者分页查询 
  12.     */ 
  13.    @RequestMapping(method = RequestMethod.GET) 
  14.    public String getUserList(ModelMap map) { 
  15.        map.addAttribute("userList", userService.findAll()); 
  16.        return "userList"
  17.    } 
  18.  
  19.    /** 
  20.     * 显示创建用户表单 
  21.     * 
  22.     */ 
  23.    @RequestMapping(value = "/create", method = RequestMethod.GET) 
  24.    public String createUserForm(ModelMap map) { 
  25.        map.addAttribute("user", new User()); 
  26.        map.addAttribute("action""create"); 
  27.        return "userForm"
  28.    } 
  29.  
  30.    /**
  31.     *  创建用户 
  32.     *    处理 "/users" 的 POST 请求,用来获取用户列表 
  33.     *    通过 @ModelAttribute 绑定参数,也通过 @RequestParam 从页面中传递参数 
  34.     */ 
  35.    @RequestMapping(value = "/create", method = RequestMethod.POST) 
  36.    public String postUser(@ModelAttribute User user) { 
  37.        userService.insertByUser(user); 
  38.        return "redirect:/users/"
  39.    } 
  40.  
  41.    /** 
  42.     * 显示需要更新用户表单 
  43.     *    处理 "/users/{id}" 的 GET 请求,通过 URL 中的 id 值获取 User 信息 
  44.     *    URL 中的 id ,通过 @PathVariable 绑定参数 
  45.     */ 
  46.    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) 
  47.    public String getUser(@PathVariable Long id, ModelMap map) { 
  48.        map.addAttribute("user", userService.findById(id)); 
  49.        map.addAttribute("action""update"); 
  50.        return "userForm"
  51.    } 
  52.  
  53.    /** 
  54.     * 处理 "/users/{id}" 的 PUT 请求,用来更新 User 信息 
  55.     * 
  56.     */
  57.    @RequestMapping(value = "/update", method = RequestMethod.POST) 
  58.    public String putUser(@ModelAttribute User user) { 
  59.        userService.update(user); 
  60.        return "redirect:/users/"
  61.    } 
  62.  
  63.    /** 
  64.     * 处理 "/users/{id}" 的 GET 请求,用来删除 User 信息 
  65.     */
  66.    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) 
  67.    public String deleteUser(@PathVariable Long id) { 
  68.  
  69.        userService.delete(id); 
  70.        return "redirect:/users/";
  71.    } 
  72.  

ModelMap 对象来进行数据绑定到视图。return 字符串,该字符串对应的目录在 resources/templates 下的模板名字。 @ModelAttribute 注解是用来获取页面 Form 表单提交的数据,并绑定到 User 数据对象。

Form 表单页面

核心代码:

 
   
  1. <form th:action="@{/users/{action}(action=${action})}" method="post" class="form-horizontal"
  2.  
  3.                <input type="hidden" name="id" th:value="${user.id}"/> 
  4.  
  5.                <div class="form-group"
  6.                    <label for="user_name" class="col-sm-2 control-label">名称</label> 
  7.                    <div class="col-xs-4"
  8.                        <input type="text" class="form-control" id="user_name" name="name" th:value="${user.name}" /> 
  9.                    </div> 
  10.                </div> 
  11.  
  12.                <div class="form-group"
  13.  
  14.                    <label for="user_age" class="col-sm-2 control-label">年龄:</label> 
  15.                    <div class="col-xs-4"
  16.                       <input type="text" class="form-control" id="user_age" name="age" th:value="${user.age}"/> 
  17.                    </div> 
  18.                </div> 
  19.  
  20.                <div class="form-group"
  21.                    <label for="user_birthday" class="col-sm-2 control-label">出生日期:</label> 
  22.                    <div class="col-xs-4"
  23.                        <input type="date" class="form-control" id="user_birthday" name="birthday" th:value="${user.birthday}"/> 
  24.                    </div> 
  25.                </div> 
  26.  
  27.                <div class="form-group"
  28.                    <div class="col-sm-offset-2 col-sm-10"
  29.                        <input class="btn btn-primary" type="submit" value="提交"/>   
  30.                        <input class="btn" type="button" value="返回" onclick="history.back()"/> 
  31.                    </div> 
  32.                </div> 
  33.            </form> 

这里定义了一个 Form 表单用于新增或者更新用户。

列表页面

代码如下:

 
   
  1. <table class="table table-hover table-condensed"
  2.                <legend> 
  3.                    <strong>用户列表</strong> 
  4.                </legend> 
  5.                <thead> 
  6.                    <tr> 
  7.                        <th>用户编号</th> 
  8.                        <th>名称</th> 
  9.                        <th>年龄</th> 
  10.                        <th>出生时间</th> 
  11.                        <th>管理</th> 
  12.                    </tr> 
  13.                </thead> 
  14.                <tbody> 
  15.                    <tr th:each="user : ${userList}"
  16.                        <th scope="row" th:text="${user.id}"></th> 
  17.                        <td><a th:href="@{/users/update/{userId}(userId=${user.id})}" th:text="${user.name}"></a></td> 
  18.                        <td th:text="${user.age}"></td> 
  19.                        <td th:text="${user.birthday}"></td> 
  20.                        <td><a class="btn btn-danger" th:href="@{/users/delete/{userId}(userId=${user.id})}">删除</a></td> 
  21.                    </tr> 
  22.                </tbody> 
  23.            </table

这里循环了用户列表。

Tymeleaf 的语法糖

我这边也就不详细展开了,大家看看人家写的 http://www.cnblogs.com/nuoyiamy/p/5591559.html 或者看看官方文档 http://www.thymeleaf.org/documentation.html

三、本文小结

该文,利用 Thymeleaf 做了个 Web 的 CRUD 案例。大家多指教~  


原文发布时间为:2017-10-17

本文作者:李强强

本文来自云栖社区合作伙伴“51CTO”,了解相关信息可以关注。