spring 对于Netty和Sping Boot 3,getRequestURI为空

8yoxcaq7  于 2022-12-02  发布在  Spring
关注(0)|答案(1)|浏览(192)

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

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

它一直工作,直到最近我升级到Sping 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

既然我在Sping Boot 3.0中使用Netty而不是Tomcat,现在还有什么选择呢?我无法从here中找到这一点。
为了解决这个问题,我现在使用的解决方法是:

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

以及

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

mklgxw1f1#

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

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

在3.1.0版中,Thymeleaf中已删除了此部分。以下是文档中的等效部分:请求/会话属性的Web上下文命名空间等。
“3.1中的新功能”documentation没有特别提到HttpServletRequest,但它确实提到删除了所有“* 基于web-API的表达式实用程序对象 *"。
Thymeleaf 3.1中的表达式不再使用#request、#response、#session和#servletContext。
Sping 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

相关问题