一. 回顾
前面Day26——引入thymeleaf讲述了引入thymeleaf的方法。下面开始使用thymeleaf。
二. 使用thymeleaf
2.1 使用thymeleaf的html页面放在哪里
在引入thymeleaf的依赖后,可以在External Libraries看到有这样一个包:
在ThymeleafProperties类中可以看到如下:
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
总结:只要我们把xxx.html页面放在classpath:/templates/,thymeleaf就能自动渲染
2.2 使用thymeleaf的小例子
- 首先我们在classpath:/templates/下创建一个success.html
- 在要使用到thymeleaf的html页面引入命名空间
xmlns:th="http://www.thymeleaf.org
(引入命名空间写thymeleaf代码会有提示,在Thymeleaf官网的doc文档里面有一个using thymeleaf的pdf,里面的using text可以查看thymeleaf的命名空间)如下:
- 写controller方法进行控制,写html页面内容
HelloController.java
@RequestMapping("/success")
public String success(Map<String, Object> map){
map.put("hello", "你好");
return "success";
}
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 th:text="${hello}"></div>
</body>
</html>
- 浏览器输入
localhost:8080/success
,即可看到success.html页面的内容
如果没有跳转到success.html,99%都是在Controller加了@RestController或者在controller方法加了@ResponseBody。加了这两个注释,会将return后面的内容当初json串返回给客户端,所以是跳转不到success.html的