Thymeleaf的简单使用介绍

本文介绍Thymeleaf模板引擎的特点与SpringBoot的整合,包括基本语法、页面静态化及与Nginx的配合使用,提升页面并发处理能力。

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

1.Thymeleaf简介

官方网站:https://www.thymeleaf.org/index.html

特点

1.1    动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。。
1.2   与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。

1.3  与前端技术的比较
在这里插入图片描述
因为Thymeleaf没有使用自定义的标签或语法,所有的模板语言都是扩展了标准H5标签的属性

<div  th:text="${item.skuName} "></div>

1.4 pom.xml

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

2.Thymeleaf的基本用法

2.1 头文件就像Jsp的<%@Page %>一样 ,Thymeleaf的也要引入标签规范。

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

2.2 取出请求域中的值,如果不写打底值,没拿到hello这个属性值则会报错

<p th:text="${hello}">打底值</p>

3.3 循环

<table border="1">
    <tr th:each="skuImage:${skuInfo.skuImageList}">
        <td th:text="${skuImage.id}">
        </td>
        <td th:text="${skuImage.imgName}">
        </td>
      </tr>
</table>

3.4 表达式和判断

<td th:text="(${skuImage.id}=='10')?'是10':'不是10'">
</td>
<td th:if="${skuImage.id}=='10'" >123456</td>


3.工程搭建

使用spring 脚手架创建:
在这里插入图片描述
勾选web和Thymeleaf的依赖
在这里插入图片描述
项目结构
在这里插入图片描述

不需要做任何配置,启动器已经帮我们把Thymeleaf的视图器配置完成,与jsp类似的前缀+ 视图名 + 后缀风格:
在这里插入图片描述
Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关闭缓存,在application.properties配置:

# 关闭Thymeleaf的缓存(热部署)
spring.thymeleaf.cache=false

另外,修改完毕页面,需要使用快捷键:Ctrl + Shift + F9来刷新工程。


4.快速开始

我们准备一个controller,控制视图跳转:

@Controller
public class HelloController {

    @GetMapping("show1")
    public String show1(Model model){
        model.addAttribute("msg", "Hello, Thymeleaf!");
        return "hello";
    }
}

新建一个html模板:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
    <h1 th:text="${msg}">大家好</h1>
</body>
</html>

启动项目,访问页面:
在这里插入图片描述

5.页面静态化

静态化是指把动态生成的HTML页面变为静态内容保存,以后用户的请求到来,直接访问静态页面,不再经过服务的渲染。
而静态的HTML页面可以部署在nginx中,从而大大提高并发能力,减小tomcat压力。

TemplateEngine:模板引擎:用来解析模板的引擎,需要使用到上下文、模板解析器。分别从两者中获取模板中需要的数据,模板文件。
context: 上下文,用来保存模型数据
writer: 输出目的地的流。

templateEngine.process("模板名", context, writer);

具体实现:

@Service
public class GoodsHtmlService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);

    /**
     * 创建html页面
     *
     * @param spuId
     * @throws Exception
     */
    public void createHtml(Long spuId) {

        PrintWriter writer = null;
        try {
            // 获取页面数据
            Map<String, Object> spuMap = this.goodsService.loadModel(spuId);

            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariables(spuMap);

            // 创建输出流
            File file = new File("C:\\project\\nginx-1.14.0\\html\\item\\" + spuId + ".html");
            writer = new PrintWriter(file);

            // 执行页面静态化方法
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            LOGGER.error("页面静态化出错:{},"+ e, spuId);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}

当页面第一次访问,则正常访问controller方法,顺便调用生成静态页面的方法:

@GetMapping("{id}.html")
public String toItemPage(@PathVariable("id")Long id, Model model){

    // 加载所需的数据
    Map<String, Object> map = this.goodsService.loadModel(id);
    // 把数据放入数据模型
    model.addAllAttributes(map);

    // 页面静态化
    this.goodsHtmlService.asyncExcute(id);

    return "item";
}

配置nginx拦截已有的页面:

server {
    listen       80;
    server_name  www.leyou.com;

    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location /item {
        # 先找本地
        root html;
        if (!-f $request_filename) { #请求的文件不存在,就反向代理
            proxy_pass http://127.0.0.1:8084;
            break;
        }
    }

    location / {
        proxy_pass http://127.0.0.1:9002;
        proxy_connect_timeout 600;
        proxy_read_timeout 600;
    }
}

重启nginx:nginx -s reload
测试,发现生成后的静态页面访问速度得到了极大提升

<think>嗯,用户想了解Thymeleaf使用方法、教程和示例。首先,我需要根据用户提供的引用内容来组织信息。引用[1]提到了Thymeleaf分页和排序的示例,引用[2]和[3]涉及变量表达式和布尔属性的使用,引用[4]看起来是关于Spring的自动注入。可能用户是在使用Spring Boot整合Thymeleaf,需要相关的指导。 首先,我应该介绍Thymeleaf的基本语法,比如变量表达式${},选择表达式*{},还有链接表达式@{}。然后结合引用中的例子,比如分页和排序的实现,可能需要用到th:each和th:href这样的属性。同时,用户可能想知道如何与Spring Data结合,比如分页对象的传递和处理。 接下来,模板布局部分,用户可能希望知道如何复用页面,比如头部和尾部,所以需要提到th:insert和th:replace。引用[3]中的布尔属性处理,比如th:checked,也是需要强调的点。 然后,结合Spring Boot的整合步骤,需要提到依赖添加、配置以及Controller中如何传递Model数据。可能还需要给出一个简单的示例代码,展示如何在Controller里设置变量,并在Thymeleaf模板中使用它。 关于分页和排序的具体示例,引用[1]中的例子可能需要详细展开,比如使用Spring Data的Page对象,如何在Thymeleaf中生成分页链接,处理排序参数等。这部分可能需要步骤说明,包括后端Controller的处理和前端的Thymeleaf标签使用。 用户可能遇到的常见问题包括表达式语法错误、Spring Bean的注入问题,比如引用[4]中的自动注入是否正确,或者Thymeleaf与Spring Security的整合,这些可以作为注意事项提醒用户。 最后,生成的相关问题需要围绕用户可能进一步想了解的内容,比如表达式语法细节、与Spring Boot的整合步骤、常见问题解决,以及更高级的功能如布局和表单处理。这样可以帮助用户深入探索他们感兴趣的部分。</think>### Thymeleaf 使用方法与示例教程 #### 一、基础语法与应用 1. **变量表达式** 使用`${}`获取模型数据(基于Spring MVC的Model对象),支持嵌套属性访问。例如显示用户名称: ```html <span th:text="${user.name}">默认名称</span> ``` 引用自Spring Data整合示例中的分页数据传递[^1]。 2. **链接表达式** 通过`@{}`生成动态URL,常用于资源路径和请求路由: ```html <a th:href="@{/users/list(page=1)}">第一页</a> ``` 3. **条件与循环** - 条件判断:`th:if/th:unless` ```html <div th:if="${user.isAdmin}">管理员面板</div> ``` - 循环遍历:`th:each` ```html <tr th:each="item : ${items}"> <td th:text="${item.id}"></td> </tr> ``` #### 二、与Spring Boot整合步骤 1. **添加依赖** 在`pom.xml`中引入: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2. **配置视图解析器** `application.properties`配置模板路径: ```properties spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html ``` 3. **Controller示例** ```java @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/users") public String listUsers(Model model, @PageableDefault Pageable pageable) { Page<User> users = userService.findAll(pageable); model.addAttribute("users", users); // 传递分页数据到模板[^1] return "user/list"; } } ``` #### 三、分页与排序实现(引用自) 1. **分页按钮生成** ```html <div class="pagination"> <a th:href="@{/users(page=0)}">首页</a> <a th:each="i : ${#numbers.sequence(1, users.totalPages)}" th:href="@{/users(page=${i-1})}" th:text="${i}"></a> </div> ``` 2. **列标题排序** ```html <th> <a th:href="@{/users(sort='name,desc')}">姓名▼</a> </th> ``` #### 四、注意事项 1. **表达式与注入问题** - 使用`${}`时需确保Model中已注入对应变量[^2] - 避免在模板中直接调用业务逻辑方法 - 自动注入需正确使用`@Autowired`(如引用[4]中的类导入问题) 2. **布尔属性处理** 通过`th:*`属性动态控制复选框等元素状态: ```html <input type="checkbox" th:checked="${rememberMe}" /> 记住我[^3] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值