美文网首页
springboot整合Thymeleaf

springboot整合Thymeleaf

作者: iDevOps | 来源:发表于2019-11-09 18:33 被阅读0次

springboot不推荐使用jsp, 所以我们这里学习下Thymeleaf。

为什么选择Thymeleaf?
  • 动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • 开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • 多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
  • 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。
使用Thymeleaf
  • 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 编写接口
@Controller
public class UserController {

    @GetMapping("/users")
    public String users(ModelMap modelMap){
        List<User> users = new ArrayList<>();
        users.add(new User(1, "张三"));
        users.add(new User(2, "李四"));
        // 放入模型
        modelMap.addAttribute("users", users);
       // 返回模板名称(就是classpath:/templates/目录下的html文件名)
        return "users";
    }

}
  • 静态页面
    /resources/tempates/users.html
<!DOCTYPE html>
<!--注意,把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org" 会有语法提示-->
<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>
<!--
${} :这个类似与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能够动静结合的原因,模板解析失败不影响页面的显示效果,因为会显示默认值!
-->
<div style="text-align: center">
    <table class="list">
        <tr>
            <th>id</th>
            <th>姓名</th>
        </tr>
        <tr th:each="user : ${users}">
            <td th:text="${user.id}">1</td>
            <td th:text="${user.name}">张三</td>
        </tr>
    </table>
</div>
</body>
</html>
  • application.yml
spring:
  thymeleaf:
    cache: false  # 开发阶段可以关闭缓存
  • 测试


    测试页面

相关文章

网友评论

      本文标题:springboot整合Thymeleaf

      本文链接:https://www.haomeiwen.com/subject/depnbctx.html