Spring Boot中Thymeleaf模板引擎的使用
一.什么是Thymeleaf引擎
Thymeleaf是面向Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本。SpringBoot默认使用的就是themeleaf模板引擎。
创建工程
1.创建Spring Boot工程,pom.xml文件中加入Thymeleaf的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在application.propertise文档中配置thymeleaf信息
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
3.写控制器
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserContrller {
@RequestMapping("/test")
public String test(){
System.out.println("hello...");
return "hello";
}
}
这边注意是@Controller注解,不是@RestController。这两者区别可以参考
@Controller和@RestController区别
4.写html
templates文件夹下创建hello.html
<body>
<h2>hello spring boot</h2>
</body>
5.启动项目,测试