【问题标题】:getRequestURI is null with Netty and Spring Boot 3对于 Netty 和 Spring Boot 3,getRequestURI 为空
【发布时间】:2022-12-22 22:44:00
【问题描述】:

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

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

它一直有效,直到最近我升级到拉取 Thymeleaf 3.1 的 Spring Boot 3.0。我得到这个例外:

[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

既然我在 Spring Boot 3.0 中使用 Netty 而不是 Tomcat,现在有什么选择?我无法从here 中得出这一点。

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

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

th:classappend="${pagename == 'home' ? 'active' : ''}"

【问题讨论】:

    标签: spring spring-boot thymeleaf spring-thymeleaf


    【解决方案1】:

    在 Thymeleaf 3.0 中,提供了对 HttpServletRequest 的访问:

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

    这已在 3.1.0 中从 Thymeleaf 中删除。这是文档中的等效部分:Web context namespaces for request/session attributes, etc.


    “what's new in 3.1”documentation没有特别提到HttpServletRequest,但确实提到删除所有“基于 web-API 的表达式实用程序对象”。

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

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


    该怎么办?

    查看相关的GitHub问题:Recommended way to go after upgrade to SpringBoot3 - attributes

    具体来说:

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

    例子:

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

    这与您在变通办法中已经在做的基本方法相同。


    另见:Remove web-API based expression utility objects

    【讨论】:

    • 你真棒@andrewJames。我完全忽略了 3.1 中的新功能文档中的第 1.6 节。非常感谢您的时间和精力。
    猜你喜欢
    • 2021-05-14
    • 2017-10-29
    • 2019-07-11
    • 2018-07-14
    • 2018-03-17
    • 2017-03-27
    • 2020-06-03
    • 2020-11-20
    • 1970-01-01
    相关资源
    最近更新 更多