springboot08 thymeleaf 语法 & 小案例巩固

1、不想看系列

thymeleaf 是一种模板引擎,所谓引擎就是将动态的数据放入静态的html界面,然后渲染出一个新的html页面。

其实jsp就是一种模板引擎,但是和thymeleaf不一样的是,前端写好的html,需要先转成jsp格式,然后再内嵌使用Java代码,用过的同志就知道,Java代码和html标签杂乱不堪,所以过时也是因为这个原因,那thymeleaf就不一样了么?

确实不一样,它和vue有异曲同工之妙,将标签绑定,放入固定的数据,然后渲染出来,前端的html页面你甚至拿来即用,里面你看不到Java代码,它的职责很明确,他就是接到数据渲染页面的。

但是体会过前后端分离的我,还是觉得分离真香。

2、hello thymeleaf

2.1 引入依赖

按照springboot的习惯,我们只需要引入一个starter就好了

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

它会默认帮我们导入
在这里插入图片描述
所以其实不用导starter,导那两个依赖也是等价的

2.2 创建hello.html

在哪创建呢?根据前面的文章,spring boot的自动装配原理,我们全局搜索ThymeleafProperties
在这里插入图片描述
所以我们需要在classpath:/templates/目录中创建.html结尾的文件,这是默认的,也就是说可以修改的,修改就不必多言了。

spring:
  thymeleaf:
    prefix: classpath:/butcher/
    suffix: .jsp

就可以修改它为classpath:/butcher/目录中创建.jsp结尾的文件。

好,话多了,我们创建一个hello.hrml文件

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>

根据官网,你要在html中使用thymeleaf,你需要在html标签那加一个命名空间

xmlns:th="http://www.thymeleaf.org"

在这里插入图片描述
th:text="${msg}"取出我们传过来的模板数据

2.3 编写controller

package cn.butcher.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String sayHello(Model model){
        model.addAttribute("msg","hello thymeleaf!");
        return "hello";
    }
}

启动!访问/hello请求
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值