什么是thymeleaf
如何使用thymeleaf
1.导入依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
2.建template包,存放html文件
3.controller视图跳转
@Controller
public class TestController {
@GetMapping("/test")
public String test(){
return "test";
}
}
4.见效果
注意:
如果视图叫index.html,那么会覆盖首页,也就是localhost:8080/就会显示index.html,这里在源码中可以体现出。
如何实现服务器首页的覆盖,以及它的底层原理?
private Resource getIndexHtml(Resource location) {
try {
Resource resource = location.createRelative("index.html");
if (resource.exists() && resource.getURL() != null) {
return resource;
}
} catch (Exception var3) {
}
return null;
}
在启动器的自动配置下的web场景下的WebMvcAutoConfiguration配置类里的getIndexHtml方法里创建一个相对路径index.html作为我们的默认路径,如果存在这样的路径,就返回该资源给到首页,于是帮就覆盖首页了。
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
ThymeleafProperties 类中实质就是一个视图解析器,配置了前缀和后缀的默认值。并且编码也配好了,不用我们再去写编码的过滤器。
thymeleaf语法
$获取表达式
<p th:text="'Hello!, ' + ${name} + '!'" >name</p>
@{url}
<a th:href="@{http://www.baidu.com}">绝对路径</a>
<a th:href="@{/}">相对路径</a>
<a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>
条件if/unless
Thymeleaf 中使用 th:if 和 th:unless 属性进行条件判断,下面的例子中,标签只有在 th:if 中条件成立时才显示:
<a th:href=“@{/login}” th:unless=${session.user != null}>Login
th:unless 与 th:if 恰好相反,只有表达式中的条件不成立,才会显示其内容。