spring-boot项目中如何集成使用thymeleaf

本文介绍如何在Spring Boot项目中配置并使用Thymeleaf模板引擎,包括依赖引入、控制器设置及模板文件读取,适用于初学者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、引入依赖(可在新建项目时勾选thymeleaf)

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

二、设置模板信息

@Controller
public class SysUserController {
    @GetMapping("/")
     public ModelAndView index(HttpSession session){
        Object username = session.getAttribute("username");
        if(username==null){
            username="张三";
            session.setAttribute("username",username);
        }
        ModelMap model = new ModelMap("message","个人信息减价")
                          .addAttribute("username",username)
                          .addAttribute("title",username)
                          .addAttribute("date",new Date())
                          .addAttribute("foot","哈哈");
         return  new ModelAndView("index",model);
    }
}

三、读取模板信息

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf</title>
    <link rel="stylesheet" th:href="@{~/css/app.css}">
</head>
<body>
<section>
    <header>
        <h1 th:text="${title}">标题</h1>
    </header>
    <article>
        <div>
            <p th:text="${username}">用户名</p>
            <p th:text="${#calendars.format(date,'yyyy-MM-dd')}">日期</p>
        </div>
        <p th:text="${message}"></p>
    </article>
    <footer th:text="${foot}">注脚</footer>
</section>

</body>
</html>

参考: https://blog.youkuaiyun.com/f0rd_/article/details/80580225

https://jingyan.baidu.com/album/2a138328edd242074a134fce.html?picindex=6

转载于:https://my.oschina.net/u/2427561/blog/2251711

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值