SpringBoot整合Thymeleaf

一、简介

Thymeleaf是一个强大可扩展的服务端java模板引擎。
官网地址:https://www.thymeleaf.org/

1.1 可处理六种模板模式
 - HMTL
 - XML
 - TEXT
 - JAVASCRIPT
 - CSS
 - RAW
1.2 常用表达式
 - 变量表达式:${...}
 - 选择变量表达式:*{...}
 - 消息表达式:#{...}
 - 链接url表达式:@{...}
 - 片段表达式:~{...}
1.3 设置任一属性的值
举例
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
可以设置多个属性的值,中间用逗号隔开
1.4 设置特定标签(th:*)
举例
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/

二、SpringBoot集成Thymeleaf

2.1 添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.2 修改配置
spring:
  thymeleaf:
    servlet:
      content-type: text/html
    mode: HTML
    # 模板路径,此为默认
    prefix: classpath:/templates/
    encoding: UTF-8
    # 模板后缀
    suffix: .html
    # 设置为false,不缓存,避免修改需要重启
    cache: false
2.3 测试代码
  • web层
@RequestMapping(value = "/test")
   public  ModelAndView test(){
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.setViewName("test");
       return modelAndView;
   }
}
  • templates下的test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<body>
   <input th:value="111"/>
</body>
</html>
  • 验证页面效果
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合Thymeleaf是一种常见的做法,用于在Spring Boot应用中利用Thymeleaf作为模板引擎,提供动态网页功能。Thymeleaf是一个强大的、现代的Web模板引擎,支持HTML5和XML。 以下是整合步骤: 1. 添加依赖:在你的`pom.xml`文件中添加Thymeleaf及其Spring Boot支持的依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> ``` 2. 配置视图解析器:在`application.properties`或`application.yml`中设置Thymeleaf的视图位置: ``` spring.thymeleaf.views.location=classpath:/templates/ ``` 3. 创建模板目录:在项目的`src/main/resources/templates`目录下创建HTML模板文件。 4. 使用Thymeleaf标签:在模板文件中,你可以使用Thymeleaf的表达式语言(EL)和特殊语法,如条件语句、迭代等。 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>My Spring Boot App</title> </head> <body> <h1 th:text="${message}">Hello, World!</h1> </body> </html> ``` 5. 在Controller中返回模型数据并指定视图:例如: ```java import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { @GetMapping("/") public String home(Model model) { model.addAttribute("message", "Welcome to Spring Boot with Thymeleaf!"); return "home"; // 指定模板名称 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值