Netty 和 Spring Boot 3 中 getRequestURI 为 null

Aja*_*mar 5 spring thymeleaf spring-boot spring-thymeleaf

在 Thymeleaf < 3.1 中,我使用下面的表达式来获取请求 URI。

th:classappend="${#arrays.contains(urls, #httpServletRequest.getRequestURI()) ? 'active' : ''}"
Run Code Online (Sandbox Code Playgroud)

它一直有效,直到最近我升级到了 Spring Boot 3.0,它拉动了 Thymeleaf 3.1。我收到此异常:

[THYMELEAF][parallel-2] Exception processing template "index": Exception evaluating SpringEL expression: "#arrays.contains(urls, #servletServerHttpRequest.getRequestURI()) ? 'active' : ''" (template: "fragments/header" - line 185, col 6)

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getRequestURI() on null context object
Run Code Online (Sandbox Code Playgroud)

既然我在 Spring Boot 3.0 中使用 Netty 而不是 Tomcat,那么现在有什么替代方案吗?我无法从这里弄清楚这一点。

作为解决方法,现在为了解决这个问题,我正在使用:

@GetMapping ("/")
String homePage(Model model) {
    model.addAttribute("pagename", "home");
    return "index";
}
Run Code Online (Sandbox Code Playgroud)

th:classappend="${pagename == 'home' ? 'active' : ''}"
Run Code Online (Sandbox Code Playgroud)

and*_*mes 11

在 Thymeleaf 3.0 中,提供了以下访问权限HttpServletRequest

#request :直接访问与当前请求关联的 javax.servlet.http.HttpServletRequest 对象。参考

这已在 3.1.0 中从 Thymeleaf 中删除。以下是文档中的等效部分:请求/会话属性的 Web 上下文命名空间等


“3.1 中的新增功能”文档没有具体提及HttpServletRequest,但确实提到删除所有“基于 Web-API 的表达式实用程序对象”。

#request、#response、#session 和 #servletContext 不再可用于 Thymeleaf 3.1 中的表达式。

Spring Boot 3.0.0 使用 Thymeleaf 3.1.0(如您所述)。


该怎么办呢?

请参阅相关的 GitHub 问题:升级到 SpringBoot3 后推荐的方式 - 属性

具体来说:

出于安全原因,这些对象不能直接在 Thymeleaf 3.1 的模板中使用。使这些信息可供模板使用的推荐方法是将模板真正需要的特定信息添加为上下文变量(Spring 中的模型属性)。

例子:

model.addAttribute("servletPath", request.getServletPath();

这与您在解决方法中已经采取的基本方法相同。


另请参阅:删除基于 Web-API 的表达式实用程序对象