首页 > 解决方案 > 如何在 Spring MVC 中获取 HttpServletRequest?

问题描述

如何在 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.

请告诉我如何解决这个问题?

    @Component
    public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {


        @Autowired
        private HttpServletRequest request;


        @Override
        public void onApplicationEvent(AuthenticationSuccessEvent a) {
            
            System.out.println(request.getRemoteAddr());
            
        }

    }

标签: javaspringspring-mvcspring-security

解决方案


你能试试这个

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>

推荐阅读