springboot模板引擎Thymeleaf

Thymeleaf

  1.导入依赖

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

  2.查看源码

  

 

  thymeleaf的html都写在resources/templates下

  3.测试前端代码

  注意添加命名空间

 xmlns:th="http://www.thymeleaf.org"
复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>测试页面</h1>
<div th:text="${msg}"></div>

</body>
</html>
复制代码

  4.后台请求代码

复制代码
package com.chen.boot.controller;

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

@Controller
public class TestController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","success");
        return "test";
    }

}
复制代码

  5.抽取公共部分

  写一个commom.html

  将网页中公共的引入css 引js 还有别的公共代码写出来

  并在公共部分    使用 th:fragment="commonheader"   或者用id选择器  将公共部分声明

  

 

  当我们使用公共部分的时候。使用th:insert  th:peplace  th:include   (这三者是不一样的!!)

  

 

    使用 th:fragment="commonheader"  的我们直接 th:include="公共页面名字 ::  commonheader" 即可

    使用id选则器的话  我们要加#   th:include="公共页面名字 ::  #commonleftmeun" 

   

 7.遍历后台数据

复制代码
@GetMapping("/dynamic_table")
    public String dynamic_table(Model model){
        //新建几个对象放到列表里面,传给前台,前台去遍历到表格中


        List<User> users = Arrays.asList(new User("chen", "123"),
                new User("chen2", "456"),
                new User("chen3", "789"));
        model.addAttribute("userList",users);

        return "table/dynamic_table";
    }
复制代码

  遍历使用   th:each="自定义参数:${列表名字}"  这个例子里面的stats是Thymeleaf的公共部分,表示遍历列表的状态

 

posted @   qwedfrgh  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示