You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot+Thymeleaf中ServletUriComponentsBuilder加载权限问题求助

解决Thymeleaf中ServletUriComponentsBuilder访问权限问题

问题根源

Spring Boot 3(基于Spring 6)对SpEL表达式的访问做了严格安全限制,默认禁止在Thymeleaf模板中直接调用ServletUriComponentsBuilder这类静态工具类,因此会抛出"Access is forbidden"异常,进而导致浏览器卡顿。

解决方案

方案1:配置允许访问目标类

在application.properties(或application.yml)中添加配置,开放Thymeleaf对ServletUriComponentsBuilder的访问权限:

spring.thymeleaf.springel.allowable-classes=org.springframework.web.servlet.support.ServletUriComponentsBuilder

若需开放多个类,用逗号分隔类全路径即可。

方案2:避免在模板中直接调用静态类(推荐)

遵循Spring最佳实践,将URL构建逻辑移至后端,而非模板中:

  1. 创建分页URL构建工具类:
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.stereotype.Component;

@Component
public class PaginationUrlBuilder {

    public String buildPageUrl(int page) {
        return ServletUriComponentsBuilder.fromCurrentRequest()
                .replaceQueryParam("page", page)
                .toUriString();
    }
}
  1. 在控制器中注入工具类并添加到模型:
@Controller
public class YourController {

    private final PaginationUrlBuilder paginationUrlBuilder;

    public YourController(PaginationUrlBuilder paginationUrlBuilder) {
        this.paginationUrlBuilder = paginationUrlBuilder;
    }

    @GetMapping("/your-target-page")
    public String showPage(Model model, @RequestParam(defaultValue = "0") int page) {
        // 业务分页逻辑处理
        model.addAttribute("paginationUrlBuilder", paginationUrlBuilder);
        return "your-view-template";
    }
}
  1. 在Thymeleaf片段中调用工具方法:
<div th:fragment="controls" class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
    <a th:href="${paginationUrlBuilder.buildPageUrl(0)}">首页</a>
    <!-- 其他分页按钮逻辑 -->
</div>

方案3:修复依赖冲突问题

你添加的thymeleaf-extras-springsecurity4是适配Spring Security 4的旧版本,与Spring Boot 3完全不兼容,必须移除该依赖。同时Spring Boot Web Starter已包含spring-webmvc,无需手动引入,也应删除手动添加的spring-webmvc依赖,避免版本冲突。

修正后的核心依赖示例:

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

额外提示

执行npm run build && npm run watch后的浏览器卡顿,是模板解析失败引发的循环错误,解决权限或依赖问题后该现象会自动消失。

内容的提问来源于stack exchange,提问作者Aquarius Logics

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:01:28