集成Spring Boot Thymeleaf模板引擎使用教程

集成Spring Boot Thymeleaf模板引擎使用教程

接下来给大家讲讲在Spring Boot项目中如何使用Thymeleaf模板引擎。

Thymeleaf是一款很方便的模板引擎,可以与Spring Boot天然配合,省去了JSP等复杂的配置。

首先,我们需要在pom.xml文件中添加Thymeleaf的依赖:

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

然后,创建一个简单的Controller:

@Controller
public class DemoController {
   
   @GetMapping("/demo")
   public String demo(Model model){
       // 添加数据到模型  
      model.addAttribute("message","Hello Thymeleaf!")
       return "demo"; 
   }
}

对应一个demo.html模板:

<html xmlns:th="http://www.thymeleaf.org">
<body>
   <p th:text ="${message}">Hello World!</p>
</body>  
</html>

这时就可以通过http://localhost:8080/demo ↗ 地址访问了。

Thymeleaf模板中常用的语法为th: text来设置文本内容,th:each进行循环,th:if``th:unless进行条件判断等。

使用Thymeleaf非常方便,不需要像JSP那样写Java代码,编写起来更像HTML,前端开发者也更易上手。

总的来说,集成Thymeleaf很简单,相较于JSP更加简洁、且与HTML更加天然地融合,非常适合Spring Boot中使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值