目录

 

 

理论

演示


 

理论

使用TemplateEngine是Spring Boot中推荐的,他的作用是:

把模板(如html界面)和数据匹配好,然后输出,发给用户。

而不是传统的使用jsp进行操作

 

模版和数据交给引擎,最后给出一个界面给用户。

Thymeleaf语法简单,功能强大;

Spring Boot中Thymeleaf的初步使用

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

通过这个能在写HTML中获取Thymeleaf的提示

 

演示

运行截图如下:

Spring Boot中Thymeleaf的初步使用

程序结构如下:

Spring Boot中Thymeleaf的初步使用

源码如下:

HelloControler.java

package com.jar.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Map;


@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){

        return "Hello World";
    }

    //查出一些数据,显示到页面上
    @RequestMapping("/success")
    public String success(Map<String, Object> map){

        map.put("hello", "你好");
        map.put("HowAreYou", "<h1>咋了</h1>");
        map.put("users", Arrays.asList("zhangsan", "lisi", "wangwu"));
        return "success";
    }
}

JarApplication.java

package com.jar.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JarApplication {

    public static void main(String[] args) {
        SpringApplication.run(JarApplication.class, args);
    }

}

success.html

<!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="${hello}"></div>

    <!-- 使用th任意属性,替换原有属性 -->
    <div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">欢迎</div>


    <!-- th:text 和 th:utext的区别 -->
    <div th:text="${HowAreYou}"></div>
    <div th:utext="${HowAreYou}"></div>
    <br>
    <br>

    <!-- 遍历标签 -->
    <h4 th:text="${user}" th:each="user:${users}"></h4>
    <br>
    <h4>
        <span th:each="user:${users}">[[${user}]]</span>
    </h4>
    <!-- 结束 -->

    <h1>Hello</h1>

</body>
</html>

 

相关文章:

  • 2021-11-09
  • 2021-11-12
  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
  • 2021-07-20
猜你喜欢
  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
  • 2021-06-29
  • 2022-12-23
  • 2021-09-01
  • 2022-12-23
相关资源
相似解决方案