正文
Spring Boot入门——thymeleaf模板使用
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
使用步骤
1、在pom.xml中引入thymeleaf
<!-- thymeleaf插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.5.3.RELEASE</version>
</dependency>
2、关闭thymeleaf缓存
创建application.properties资源文件
<!-- 关闭thymeleaf缓存 -->
spring.thymeleaf.cache=false
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.content-type=text/html # Content-Type value.
spring.thymeleaf.enabled=true # Enable MVC Thymeleaf view resolution.
spring.thymeleaf.encoding=UTF-8 # Template encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
3、编写thymeleaf模板文件
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">Hello</h1>
<p th:text="${hello}"></p>
</body>
</html>
注:引入xmlns属性和th标签必不可少,否则无法正常执行
4、编写模板请求controller
@Controller
public class ThymeleafController { @RequestMapping("index")
public String indexHtml(Map<String, Object> map){
map.put("hello", "this is a thymeleaf test");
return "/NewFile";
}}
5、运行结果
6、thymeleaf默认使用2.0.0版本,设置使用3.0版本
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<thymeleaf.version>3.0.6.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
</properties>