Springboot+thymeleaf

什么是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 恰好相反,只有表达式中的条件不成立,才会显示其内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

❀༊烟花易冷ღ

觉得博客写的不错就打赏一下吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值