Spring Boot集成Thymeleaf

时间:2023-03-10 07:21:18
Spring Boot集成Thymeleaf

Thymeleaf是一个java类库,是一个xml/xhtml/html5的模板引擎,可以作为mvc的web应用的view层。
Thymeleaf提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代jsp。

Spring Boot默认就是使用thymeleaf模板引擎的,所以只需要在pom.xml加入依赖即可。

<!-- thymeleaf模板引擎  -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Thymeleaf缓存在开发过程中,肯定是不行的,那么就要在开发的时候把缓存关闭,只需要在application.properties进行配置即可:

# thymeleaf Config
spring.thymeleaf.cache=false

根据SpringBoot默认原则,脚本样式,图片等静态文件应放置在src/main/resources/static下,可以引入Bootstrap和jQuery。

Spring Boot集成Thymeleaf

编写模板文件src/main/resouces/templates/hello.html,在html文件中引入<html xmlns:th="http://www.thymeleaf.org">即变为thymeleaf

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${hello} + '!'" />
</body>
</html>

编写访问路径(com.holy.backoa.online.controller):

package com.holy.backoa.online.controller;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; /**
* 模板测试.
* @author Administrator
*
*/
@Controller
publicclass TemplateController { /**
* 返回html模板.
*/
@RequestMapping("/hello")
public String hello(Map<String,Object> map){
map.put("hello","from TemplateController.hello");
return"/hello";
} }

启动应用,输入地址:http://127.0.0.1:8080/hello 会输出:

Hello,from TemplateController.hello