springboot整合thymeleaf模板引擎

1. 在pom.xml文件引入thymeleaf的依赖。

<!-- 与Thymeleaf集成 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.在application.properties(application.yml)文件中配置thymeleaf。

# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=false
spring.resources.chain.strategy.content.paths=/**

3.新建编辑控制层代码ThymeleafController,在里面设置返回的html路径和设置返回的参数。

package com.example.demo.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class ThymeleafController {

    @RequestMapping("/hello")
    public ModelAndView hello(ModelAndView mv){
        mv.setViewName("/welcome");
        mv.addObject("title","欢迎使用Thymeleaf!");
        return mv;
    }
}

当然也可以不使用ModelAndView,也可以使用Model。

@RequestMapping("hello2")
public String hello2(Model model){
    model.addAttribute("title","第二个");
    return "welcome";
}

4.新建编辑模板文件,在resources文件夹下的templates目录,用于存放HTML等模板文件,在这新增welcome.html,添加如下代码。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>springboot-thymeleaf demo</title>
</head>
<body>
    <p th:text="'hello, ' + ${title} + '!'" />
</body>
</html>

5.启动项目,访问http://localhost:8080/hello,看到如下说明则说明整合成功。

在这里插入图片描述

6.Warning:使用Thymeleaf模板引擎时,必须在html文件上方添加该行代码使用支持Thymeleaf。

<html lang="en" xmlns:th="http://www.thymeleaf.org">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值