SpringBoot整合Thymeleaf


  • Thymeleaf 存放规则
    • 前缀路径classpath:/templates/
    • 后缀: .html
    • SpringBoot默认前缀和后缀就是 thymeleaf
    • 也就是说把 html 页面放在resources/templates/ ,thymeleaf 就能自动渲染

 

  • Thymeleaf 用法举例
    • 在pom中引入thymeleaf依赖
<!-- 引入thymeleaf依赖 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
    • 设置thymeleaf版本
<properties>
  <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
    • yml配置文件设置thymeleaf属性
spring: thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html encoding: UTF-8 content-type: text/html mode: HTML5
    • resources/templates/ 中新建 .html 测试文件
<!DOCTYPE HTML>
<!-- 导入thymeleaf -->
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <title>success</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- th:href = '@{/css/success.css}' 中的css前面的 / 不能省略,会报错 -->
    <link type='text/css' rel='styleSheet' th:href='@{/css/success.css}'/>
    <!-- 使用单引号和双引号都行 -->
    <script th:src="@{/js/test.js}"></script>
</head>
<body id="body"> <!-- ${ 读取name元素存放的内容 } }--> <h2 th:text=" 'Hello, My name is ' + ${name}"></h2> </body>
</html>
    • 编写Controller类跳转页面
package com.asimple.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/thymeleaf") public class ThymeleafController { @RequestMapping("/success") public String success(Model model) { //控制台验证是否执行
        System.out.println("This is success of thymeleaf"); //向前端传值
        model.addAttribute("name", "XiaoMing"); //跳转页面,由于配置了前缀和后缀,相当于是 /templates/success.html
        return "success"; } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM