Thymeleaf 配置与使用流程
本文最后更新于11 天前,其中的信息可能已经过时,如有错误请发送邮件到kirasu@qq.com

Thymeleaf 配置与使用流程

基于 SpringBoot 2.x / 3.x

1. 引入依赖(Maven pom.xml)

SpringBoot整合Thymeleaf,引入starter依赖即可

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

2. 默认目录约定

Thymeleaf默认读取资源路径:resources/templates/

  • 页面html文件全部放在 templates 文件夹
  • 静态资源(css/js/img)放在 resources/static/

    注意:templates下的文件不能直接通过url访问,必须由Controller跳转渲染

3. application.yml 常用配置(可选,不写也有默认值)

spring:
  thymeleaf:
    cache: false # 开发时关闭缓存,修改页面不用重启项目;生产环境开启true
    prefix: classpath:/templates/ # 模板文件前缀路径,默认
    suffix: .html # 文件后缀,默认
    encoding: UTF-8
    mode: HTML5

4. 页面html头部引入命名空间

<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

5. 后端Controller编写

@Controller
public class DemoController {
    @GetMapping("/index")
    public String index(Model model){
        // 把数据存入model,传给页面
        model.addAttribute("username","张三");
        return "index"; // 对应 templates/index.html
    }
}

6. 页面取值渲染(index.html)

<body>
    <p th:text="${username}">默认文字</p>
</body>

7. 访问测试

启动项目,访问 [http://localhost:8080/index](http://localhost:8080/index) 页面会渲染出:张三

文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇