SpringBoot 2 默认使用 Thymeleaf 3,需要引入下面的依赖:
1
| implementation('org.springframework.boot:spring-boot-starter-thymeleaf')
|
在 application.properties 中配置 Thymeleaf:
1 2 3 4 5
| spring.thymeleaf.mode=HTML5 spring.thymeleaf.cache=false spring.thymeleaf.suffix=.html spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html
|
Controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package com.xtuer;
import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping;
@Controller public class XController { @GetMapping("/hello") public String hello(ModelMap model) { model.put("username", "Alice"); return "hello.html"; } }
|
在 resources/templates
目录中创建文件 hello.html
:
1 2 3 4 5 6 7 8 9 10 11 12
| <!DOCTYPE html> <html>
<head> <meta charset="utf-8"/> </head>
<body> <span th:text="${username}">Thymeleaf</span> </body>
</html>
|
访问 http://localhost:8080/hello 就可以看到页面了