[英]How do I get the HttpServletRequest in Spring MVC?
如何在 Spring MVC 中獲取 HttpServletRequest?
嘗試獲取 HttpServletRequest 時,出現異常。
消息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: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
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: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
請告訴我如何解決這個問題?
@Component
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
@Autowired
private HttpServletRequest request;
@Override
public void onApplicationEvent(AuthenticationSuccessEvent a) {
System.out.println(request.getRemoteAddr());
}
}
您不應該在您的切面中自動裝配 HttpServletRequest,因為這會將您的切面綁定為只能對從正在執行的 HttpServletRequest 中調用的類運行。
而是在需要時使用 RequestContextHolder 來獲取請求。
private String getRemoteAddress() { RequestAttributes attribs = RequestContextHolder.getRequestAttributes(); if (attribs instanceof NativeWebRequest) { HttpServletRequest request = (HttpServletRequest) ((NativeWebRequest) attribs).getNativeRequest(); return request.getRemoteAddr(); } return null; }
你能試試這個
RequestAttributes reqAtt = RequestContextHolder.getRequestAttributes();
if (RequestContextHolder.getRequestAttributes() != null) {
HttpServletRequest req = ((ServletRequestAttributes) reqAtt).getRequest();
return req.getRemoteAddr();
}
您還需要在 web.xml 文件中添加/注冊 RequestContextListener 偵聽器。
<web-app ...>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
</web-app>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.