SpringBoot实战教程(3)| 整合Thymeleaf

Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全代替传统JSP 。

官方文档: Documentation - Thymeleaf

目录

一、初始化SpringBoot项目

二、引入依赖pom

三、application.properties配置文件

四、编写Controller类

五、编写html模板

六、运行结果展示


 一、初始化SpringBoot项目

二、引入依赖pom

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

因为模板引擎要依赖于web模块,所以同时要将 spring-boot-starter-web 同时加入。

三、application.properties配置文件

# 默认端口
server.port=80
##### Thymeleaf配置 #####
# 默认编码
spring.thymeleaf.encoding=utf-8
# HTML5规范
spring.thymeleaf.mode=HTML5
# 默认放置目录
spring.thymeleaf.prefix=classpath:/templates/
# 模板后缀格式
spring.thymeleaf.suffix=.html
# 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false

四、编写Controller类

IndexController.java
package com.csdn.controller;

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

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/hello")
public class IndexController {

    @RequestMapping("/thymeleaf")
    public String hello(ModelMap mmp) {
        // 字符串
        String str = "Thymeleaf";
        mmp.put("str", str);
        // 数组
        List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        mmp.put("arr", arr);
        // map集合
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age","28");
        map.put("sex","男");
        mmp.addAttribute("map",map);
        return "hello";
    }
}

五、编写html模板

hello.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>springboot-thymeleaf demo</title>
</head>
<body>
<p>显示字符串</p>
<div th:text="${str}" ></div>
<p>遍历数组方法一</p>
<div th:each="name:${arr}">[[${name}]]</div>
<p>遍历数组方法二</p>
<div th:each="name:${arr}" th:text="${name}"></div>
<p>遍历map</p>
<table class="layui-table" border="1">
    <tr th:each="item,userStat:${map}">
        <td th:text="${userStat.index}+1"></td>
        <td th:text="${userStat.current.key}"></td><!-- key-->
        <td th:text="${userStat.current.value}"></td><!-- value-->
    </tr>
</table>

</body>
</html>

六、运行结果展示

访问:http://localhost/hello/thymeleaf

作者:YangRoc

出处:https://www.cnblogs.com/YangRoc/p/17186453.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   Roc-xb  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

易微帮源码


易微帮官网

more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示