在 Thymeleaf 中使用 servletUriComponentsBuilder 进行分页片段

问题描述 投票:0回答:1

我正在使用带有 Maven 和 Java 17 的 Spring boot 3.1.4,正在编写 Wim Deblauwe 的书 #Taming Thymeleaf。我已经到达第 249 页,现在正在尝试实现分页。虽然我成功地显示了分页摘要,但我无法在 pagination.html 片段的顶部创建 urlBuilder 变量,这对于操作 URL 链接以提供分页按钮至关重要:

<div th:fragment="controls" class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6"   th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder)}">

一旦我尝试将上述行包含为 th:with="urlBuilder=${T(org....)}" 来加载 ServletUriComponentsBuilder,我就会重建我的片段 (npm run build && npm运行 watch),Chrome 浏览器挂起。我必须删除这一行,只保留类属性并重新加载片段才能恢复正常。当我转到 Spring boot 堆栈跟踪时,我注意到以下错误:

在 org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301) ~[attoparser-2.0.7.RELEASE.jar:2.0.7.RELEASE] ... 53个常用帧省略 导致:org.springframework.expression.EvaluationException:在此表达式上下文中禁止访问类型“org.springframework.web.servlet.support.servleturicomponentsbuilder”。

我首先查看了 pom.xml 以检查是否遗漏了任何依赖项。我的 pom.xml 与 Wim Deblauwe 的第 10 章的 GitHub 源代码一致,减去我自己的一些修改:我使用 MySQL 而不是 Postgres,我既不使用 jpearl 也不使用 Flyway。以下依赖项已添加到我的 pom.xml 中,以允许在 Thymeleaf pagination.html 片段中调用 ServletUriComponentsBuilder:

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>3.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>6.0.12</version>
    </dependency>
    

pom.xml 中添加的这些依赖项根本没有帮助。预先感谢您帮助我找到一种在 pagination.html 片段中加载 ServletUriComponentsBuilder 且没有任何错误的方法。

My pagination so far

spring-boot maven spring-data-jpa thymeleaf
1个回答
0
投票

Thymeleaf 3.1.2 中的一项更改不幸地引入了这一点。

作为解决方法,您可以在自己的代码中定义如下的包装类:


import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

public class ServletUriComponentsBuilderWrapper {

  public static ServletUriComponentsBuilder fromCurrentRequest() {
    return ServletUriComponentsBuilder.fromCurrentRequest();
  }
}

然后替换这个:

th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder)}"

with(假设您在

com.mycompany.myproject.infrastructure.web
包中创建了该类):

th:with="urlBuilder=${T(com.mycompany.myproject.infrastructure.web.ServletUriComponentsBuilderWrapper)}"

我打开了 Thymeleaf 的问题,但到目前为止没有得到进一步的信息。

© www.soinside.com 2019 - 2024. All rights reserved.