4.3 引入Thymeleaf模板引擎
模板引擎:JSP、Velocity、Freemarker、Thymeleaf
SpringBoot推荐的Thymeleaf;
语法更简单,功能更强大;
引入thymeleaf;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<properties>
<java.version>1.8</java.version>
<!-- 切换thymeleaf版本 -->
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<!-- thymeleaf2 layout1-->
<thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version></properties>
4.4 thymeleaf语法
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
使用:
1、导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 导入后该语法会有提示信息 -->
2、使用thymeleaf语法
controller:
@Controller
public class TestContorller {
@RequestMapping("/success")
public String success( Map<String,Object> map){
map.put("hello", "hello world");
return "success";
}
}
html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功!</h1>
<!--th:text 将div里面的文本内容设置为我们指定的值 -->
<div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>
启动SpringBoot,访问http://localhost:8081/success
问题:
配置thymeleaf之后跳转HTML页面不成功的问题?
return " success";这里多写了一个空格,导致找不到与之匹配的html页面,
注意:controller里return的值应该是html页面的名字,如我的html页面是“success.html",则return "success"即可