SpringBoot 整合 Thymeleaf

 一、引入thymeleaf依赖

https://mvnrepository.com/

1 <dependency>
2             <groupId>org.springframework.boot</groupId>
3             <artifactId>spring-boot-starter-thymeleaf</artifactId>
4             <version>2.4.4</version>
5         </dependency>

二、创建前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 th:text="${h1_text}"></h1>
</body>
</html>

三、后端代码

demosrcmain esourcesapplication.properties

#是否开启缓存,开发时可设置为false,默认为true
spring.thymeleaf.cache=false
#检查模板是否存在,默认为true
spring.thymeleaf.check-template=true
#检查模板位置是否存在,默认为true
spring.thymeleaf.check-template-location=true
#模板文件编码,UTF-8
spring.thymeleaf.encoding=UTF-8
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates
#Content-Type配置
spring.thymeleaf.servlet.content-type=text/html
#模板文件后缀
spring.thymeleaf.suffix=.html
#启用MVC Thymeleaf视图分辨率
spring.thymeleaf.enabled=true
#模板编码
spring.thymeleaf.mode=LEGACYHTML5
#应该中解决方案中排除的视图名称的逗号分隔列表
spring.thymeleaf.excluded-view-names=
模板编码使用LEGACYHTML5需要在pom.xml中加入nekohtml依赖
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/demo")
public class IndexController {

    @GetMapping(value = "index")
    public String showIndex(Model model) {
        model.addAttribute("h1_text", "this is a index page!");
        return "/index";
    }
}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.example.controller"})
public class DemoApplication {
    public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
    }

}

四、运行测试

原文地址:https://www.cnblogs.com/mingforyou/p/14609591.html