4

springboot(9)整合thymeleaf

 2 years ago
source link: https://wakzz.cn/2018/01/22/springboot/(9)%E6%95%B4%E5%90%88thymeleaf/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1、maven配置

springboot默认使用thymeleaf引擎,所以配置极其简单。
添加thymeleaf依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、创建thymeleaf模板

在src/main/resources下创建文件夹static、templates。
其中templates为thymeleaf模板默认路径,static为静态资源默认路径。

这里写图片描述

3、controller

@Controller
public class TestAction {

@RequestMapping("/index")
public String index(ModelMap map) {
map.put("title", "标题");
// 自动渲染templates路径下的index.html模板
// 返回的地址前不要加"/",如"/index",会导致部署后项目找不到模板
return "index";
}
}

4、thymeleaf模板:index.html

<!DOCTYPE html>
<html>
<head lang="en">
<title>Index</title>
<link href="/css/index.css" rel="stylesheet" />
</head>
<body>
<div align="center">
<h1 id="title">
<span th:text="${title}"></span>
</h1>
</div>
</body>
</html>

5、设置不校验html标签

默认情况下,thymeleaf对html标签的格式要求严格。例如缺少封闭符号/,就会抛出异常并跳转到错误页。可通过以下配置关闭html标签校验。

5.1在springboot的配置文件中添加如下配置:

spring.thymeleaf.cache=false
spring.thymeleaf.mode=LEGACYHTML5

5.2、maven添加依赖

<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.21</version>
</dependency>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK