springboot 使用thymeleaf模板

本文介绍如何在Spring Boot项目中使用Thymeleaf模板引擎,包括引入依赖、配置视图解析器、编写HTML文件及Controller实现,并提供一个展示用户列表的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.配置视图解析器
  • Thymeleaf默认开启了页面缓存,在开发的时候,应该关闭缓存.

  • 具体可以配置的参数可以查看 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties这个类,上面的配置实际上就是注入到该类中的属性值.

application.yml

spring:
  thymeleaf:
    prefix:classpath:/templates/
    suffix:.html
    mode:HTML5
    encoding:UTF-8
    content-type:text/html
#   开发时关闭缓存,不然没法看到实时页面
    cache:false
3.编写HTML

首先, 引入thymeleaf命名空间 :

<html  xmlns:th="http://www.thymeleaf.org" >

完整代码如下:

src/main/resources/templates/userList.html

<!DOCTYPE html>
<!-- 引入thymeleaf命名空间 -->
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org"
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>User List</title>
</head>
<body>
    <h1 th:inline="text">userList</h1>
    <table>
        <thead>
            <th>id</th>
            <th>姓名</th>
            <th>手机号</th>
        </thead>
        <tbody>
            <tr th:each="user,iterStat:${userList}">
            <td th:text="${user.userId}"></td>
            <td th:text="${user.nickname}"></td>
            <td th:text="${user.phoneNumber}"></td>
        </tr>
        </tbody>

    </table>

</body>
</html>
4.Controller
@Controller
@RequestMapping(value="/user")
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping(value="/list",method=RequestMethod.GET)
    public String list(Map<String,Object> map){
        map.put("userList", userService.getUserList());
        return "userList";
    }
}
5.最后效果

userList

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值