gpt4 book ai didi

java - 在 Spring MVC 的 ClientHttpRequestInterceptor 中访问 HttpSession

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:29 25 4
gpt4 key购买 nike

我使用 @Autowired 访问 Spring MVC Controller 中的 session ,如下所示:

@Autowired
private HttpSession session;

问题是,我现在可以在 ClientHttpRequestInterceptor 中访问 session 。

我尝试使用 RequestContextHolder.getRequestAttributes() 但结果是(有时 - 这是一个真正的问题)null。我也用 RequestContextHolder.currentRequestAttributes() 尝试过,但是 IllegalStateException 抛出以下消息:

No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

RequestContextListenerweb.xml中注册。

<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

当我直接在 ClientHttpRequestInterceptor 中注入(inject) session 时,同样的问题。

@Autowired
private HttpSession session;

我的问题是:如何访问 ClientHttpRequestInterceptor 中的当前 HttpSession

谢谢!

最佳答案

您可以在 ClientHttpRequestInterceptor 中使用以下内容来访问 HttpSession:

public class CustomInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request,
byte[] body,
ClientHttpRequestExecution execution) throws IOException {
HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
// get the current session without creating a new one
HttpSession httpSession = httpServletRequest.getSession(false);
// get whatever session parameter you want
String sessionParam = httpSession.getAttribute("parameter")
.toString();
}
}

关于java - 在 Spring MVC 的 ClientHttpRequestInterceptor 中访问 HttpSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com