springboot 整合thymeleaf

提供数据

1.编写一个controller方法,返回一些用户数据,放入模型中,将来在页面渲染

@GetMapping("/all")
public String all(ModelMap model) {
    // 查询用户
    List<User> users = this.userService.queryAll();
    // 放入模型
    model.addAttribute("users", users);
    // 返回模板名称(就是classpath:/templates/目录下的html文件名)
    return "users";
}

 引入启动器

1.SpringBoot会自动为Thymeleaf注册一个视图解析器

2.与解析JSP的InternalViewResolver类似,Thymeleaf也会根据前缀和后缀来确定模板文件的位置:

  • 默认前缀:classpath:/templates/

  • 默认后缀:.html

3.所以如果我们返回视图:users,会指向到 classpath:/templates/users.html

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

 

 编写html模板,渲染模型中的数据

注意,把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org" 会有语法提示

我们看到这里使用了以下语法:

  • ${} :这个类似与el表达式,但其实是ognl的语法,比el表达式更加强大

  • th-指令:th-是利用了Html5中的自定义属性来实现的。如果不支持H5,可以用data-th-来代替

    • th:each:类似于c:foreach 遍历集合,但是语法更加简洁

    • th:text:声明标签中的文本

      • 例如<td th-text='${user.id}'>1</td>,如果user.id有值,会覆盖默认的1

      • 如果没有值,则会显示td中默认的1。这正是thymeleaf能够动静结合的原因,模板解析失败不影响页面的显示效果,因为会显示默认值!

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <style type="text/css">
        table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto}
        table, th, td {border: 1px solid darkslategray;padding: 10px}
    </style>
</head>
<body>
<div style="text-align: center">
    <span style="color: darkslategray; font-size: 30px">欢迎光临!</span>
    <hr/>
    <table class="list">
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>用户名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>生日</th>
        </tr>
        <tr th:each="user : ${users}">
            <td th:text="${user.id}">1</td>
            <td th:text="${user.name}">张三</td>
            <td th:text="${user.userName}">zhangsan</td>
            <td th:text="${user.age}">20</td>
            <td th:text="${user.sex}">男</td>
            <td th:text="${user.birthday}">1980-02-30</td>
        </tr>
    </table>
</div>
</body>
</html>

测试

 

模板缓存

Thymeleaf会在第一次对模板解析之后进行缓存,极大的提高了并发处理能力。但是这给我们开发带来了不便,修改页面后并不会立刻看到效果,我们开发阶段可以关掉缓存使用:

# 开发阶段关闭thymeleaf的模板缓存
spring.thymeleaf.cache=false

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值