SpringBoot———静态资源—Thymeleaf模板及语法

静态资源

SpringBoot的静态资源一般放在这四个目录下:
在这里插入图片描述
自定义一个首页index.html,放在前三个包下用http://localhost:8080/都能访问到

<body>
<h1>这里是首页</h1>
</body>

而在templates包下的静态资源,只能通过Controller跳转访问,还需要加上Thymeleaf模板引擎才可以

Thymeleaf模板引擎

前端交给我们的是html页面,需要转成jsp页面,可以用jsp轻松实现数据的显示,及交互等,说白了jsp即使一个模板引擎。
但是SpringBoot默认是不支持jsp的,推荐使用Thymeleaf模板引擎。

    1. 导入thymeleaf依赖
<!--thymeleaf-->
<dependency>
	 <groupId>org.springframework.boot</groupId>
	 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
    1. templates包下编写test页面进行测试
    1. 编写controller后访问http://localhost:8080/t1跳转到test.html
@Controller
public class indexController {
    @GetMapping("/t1")
    public String index(){
        return "test";
    }
}

只需要把xxx.html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了,可与后端交互获取数据

    1. 修改测试demo,增加与后端的数据传输
@GetMapping("/t1")
    public String index(Model model){
        model.addAttribute("msg","这是从后端获取的数据");
        return "test";
    }
    1. test.html页面增加命名约束,访问http://localhost:8080/t1跳转到test.html
<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<h1>This is a test!</h1>
<h2 th:text="${msg}"></h2>
</body>
</html>

语法

所有的html标签都可以用Thymeleaf替换

    1. 后端传入html标签
model.addAttribute("msg","<h1>This is a test!</h1>");
    1. test.xml中用两种方法验证
<!--不会被转义,显示原数据-->
<div th:text="${msg}"></div>
<!--会被转义,显示h1中的数据-->
<div th:utext="${msg}"></div>

each遍历

    1. 后端传入数组集合
 model.addAttribute("users", Arrays.asList("Jack","Tom"));
    1. test.html中进行遍历,页面显示两个人名
<!--从user中遍历获取每个user 在text中显示-->
<h3 th:each="user:${users}" th:text="${user}"></h3>   <hr>
<!--另一种写法-->
<h3 th:each="user:${users}">[[${user}]]</h3>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值