3. SpringBoot中Web模板数据渲染展示

48 阅读1分钟

3. SpringBoot中Web模板数据渲染展示

📕 引入依赖

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

📕 resources/templates/添加index.html

image-20231031142501666

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<h2>一行</h2>
<table>
    <tr>
        <td th:text="${name} + '是一个特别漂亮知性、温柔体贴、如沐春风的女孩子'"></td>
    </tr>
    <tr>
        <td th:text="'你会对她一辈子特别好吗?(yes/no) ' + ${flag}"></td>
    </tr>
</table>

📕 application.properties 增加配置

spring.freemarker.suffix=.html

📕 TestController增加接口

@Controller
public class TestController {
​
    @GetMapping("/hello")
    public String helloTest(){
        return "hello,world";
    }
    @RequestMapping("/index")
    public String index2(ModelMap m){
        //数据也可以从数据库查询出来返回
        m.addAttribute("name", "耿晓如");
        m.addAttribute("flag", "yes");
        //返回是一个页码:src/main/resources/templates/index.html
        return "index";
    }
}
​