SpringBoot 使用Thymeleaf模板引擎

一、SpringBoot中使用Thymeleaf

    

1、在创建SpringBoot 的项目时,选择Thymeleaf的组件,或者自己手动在maven中添加库依赖:

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

2、在 application.yml(或aproperties)中添加相应的配置:

server:
  port: 80

# thymeleaf 配置
spring:
  thymeleaf:
    # 是否使用缓存,开发阶段最填false
    cache: false
    # 检查该模板是否存在
    check-template-location: true
    # 模板中内容的类型
    servlet:
      content-type: text/html
    # 启动 MVC 对Thymeleaf 视图的解析
    enabled: true
    # 模板的字符集
    encoding: UTF-8
    # 从解析中排除的视图名称的逗号分隔列表,没有的话就为空
    excluded-view-names:
    # 使用的是什么类型模板
    mode: HTML5
    # 设定文件路径
    prefix: classpath:/templates/
    # 设定文件后缀名
    suffix: .html

  # 设定静态文件路径,js,css等
  mvc:
    static-path-pattern: /static/**

3、新建一个controller类

@Controller
public class IndexController {

    @GetMapping("/index")
    public String indexJsp(Model model){
        User user = new User();
        user.setUsername("张三");
        user.setAge(18);
        user.setBirthday(new Date());
        User user2 = new User();
        user2.setUsername("李四");
        user2.setAge(17);
        user2.setBirthday(new Date());

        List userList = new ArrayList<>();
        userList.add(user);
        userList.add(user2);
        model.addAttribute("userList", userList);
        return "indexThymeleaf";
    }
}

4、新建一个.html页面文件

      加上名称空间,就会有thymeleaf的代码提示

<html lang="en" xmlns:th="http://www.thymeleaf.org">

      接下来便可以使用th:标签库中的方法了。这些方法和jsp极其相像

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h4>Thymeleaf首页</h4>
    <img src="../static/img/abc23.jpg" width="200px" height="100px"> <br>
    <table border="1" cellpadding="0" cellspacing="0">
        <tr>
            <td>用户名</td>
            <td>密码</td>
            <td>年龄</td>
            <td>出生年月</td>
        </tr>
        <div th:each="user:${userList}">
            <tr>
                <td th:text="${user.username}"></td>
                <td th:text="${user.pazzword}">空值</td>
                <td th:text="${user.age}"></td>
                <td th:text="${#dates.format(users.birthday,'yyyy-MM-dd HH:mm:ss')}"></td>
            </tr>
        </div>
    </table>
</body>
</html>

5、启动项目访问即可

  

二、Thymeleaf 标签使用

    Thymeleaf 官方文档

   标签参考文章:https://www.cnblogs.com/beyrl-blog/p/6633182.html

 

end ~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值