SpringBoot4-Web2-模版引擎
模版引擎
常见的模版引擎有JSP,Velocity,Freemarker,Thymeleaf ### SpringBoot推荐的Thymeleaf 1
2
3
4
5<!-- 模版引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>1
2
3
4<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.versoin>2.1.1</thymeleaf-layout-dialect.version>
</properties>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Properties for Thymeleaf.
*
* @author Stephane Nicoll
* @author Brian Clozel
* @author Daniel Fernández
* @author Kazuki Shimizu
* @since 1.2.0
*/
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20package com.wsx.springboothelloworld.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
public class HelloController {
// 把这个类的所以方法返回给浏览器,转化为json数据
public String hello() {
return "hello world quick!";
}
public String templates_hello() {
return "templates_hello";
}
}
使用
thymeleafspring.pdf 在3.1中找到如下片段 导入名称空间 1
2
3
4
5
6
7
8
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" media="all" href="../../css/gtvg.css" th:href="@{/css/gtvg.css}"/>
</head>
<body><p th:text="#{home.welcome}">Welcome to our grocery store!</p></body>
</html>1
2
3
4
5
public String templates_hello(Map<String,Object> map) {
map.put("hello","map.put(hello,hello)");
return "templates_hello";
}1
2
3
4
5
6
7
8
9
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Good Thymes Virtual Grocery</title>
</head>
<body>
<h1>这个来自templates_hello.html</h1>
<div th:text="${hello}"></div>
</body>
</html>