SpringBoot系列:4、整合thymeleaf

Thymeleaf是新一代的Java模版引擎,与Velocity、FreeMarker等传统Java模版引擎类似,支持HTML原型,前端开发人员可以在浏览器中直接查看样式,也可以让后端开发人员结合数据查看展示效果。

1、创建工程添加依赖

新建一个springboot-thymeleaf工程,添加spring-boot-starter-web和spring-boot-starter-thymeleaf依赖

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

2、Thymeleaf相关配置

  • 自动配置类:ThymeleafAutoConfiguration
  • 相关属性配置:ThymeleafProperties
  • application.yml配置
spring:
  thymeleaf:
    cache: false #是否开启缓存,开发时可以设置为false,默认为true
    check-template: true  # 检查模版是否存在,默认为true
    check-template-location: true   # 检查模版位置是否存在,默认为true
    encoding: utf-8   # 模版文件编码
    prefix: classpath:/templates/   # 模版文件位置
    servlet:
      content-type: text/html  # Content-Type配置
    suffix: .html  # 模版文件后缀

3、相关核心代码

3.1 创建User实体类

public class User {

    private Long id;
    private String name;
    private Integer age;

    // 省略getter、setter、toString方法
}

3.2 创建UserController返回ModelAndView

@Controller
public class UserController {

    @GetMapping(value = "/users")
    public ModelAndView users() {
        List<User> users = new ArrayList<>();
        User user1 = new User();
        user1.setId(1L);
        user1.setName("xiaoH");
        user1.setAge(29);

        User user2 = new User();
        user2.setId(2L);
        user2.setName("萧炎");
        user2.setAge(29);

        users.add(user1);
        users.add(user2);

        ModelAndView mv = new ModelAndView();
        mv.addObject("users", users);
        mv.setViewName("users");

        return mv;

    }
}

3.3 创建视图

在resources/templates目录下创建users.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
    <table>
        <tr>
            <td>用户id</td>
            <td>姓名</td>
            <td>年龄</td>
        </tr>
        <tr th:each="user:${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.age}"></td>
        </tr>
    </table>
</body>
</html>

3.4 运行SpringbootThymeleafApplication

浏览器访问:http://localhost:8080/users

file

4、源码

GitHub:https://github.com/chenjiecg/SpringBoot.git

5、Thymeleaf详细用法

可以参考官方文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#the-template-engine

本文由博客一文多发平台 OpenWrite 发布!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容