springboot整合Thymeleaf

2019-11-09  本文已影响0人  iDevOps

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

为什么选择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";
    }

}
<!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>
spring:
  thymeleaf:
    cache: false  # 开发阶段可以关闭缓存
上一篇 下一篇

猜你喜欢

热点阅读