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

1、引入依賴(可在新建項目時勾選thymeleaf)css

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

2、設置模板信息html

@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);
    }
}

3、讀取模板信息spring

<!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.csdn.net/f0rd_/article/details/80580225session

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

相關文章
相關標籤/搜索