繁体   English   中英

如何在 Spring MVC 中获取 HttpServletRequest?

[英]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; }

https://stackoverflow.com/a/24029989/11985558

你能试试这个

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM