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

问题描述

我正在使用 Spring MVC。我没有使用 Spring BOOT。

HttpServletRequest 对我不起作用,或者说它起作用,但仅在控制器中起作用,但在其他类中不起作用。

例如,我创建了一个 AuthenticationSuccessEventListener 类并将其标记为实现 ApplicationListener 接口的@Component。在这个类 AuthenticationSuccessEventListener 中,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.

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

https://github.com/MyTestPerson/mysite/tree/master/src/main/java/com/mysite/security/listener

AuthenticationSuccessEventListener

    @Component
    public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {


    //    This option doesn't work.
    //
    //    @Autowired
    //    HttpServletRequest httpServletRequest;

    //    And this option doesn't work.
    //
    //    HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
    //                .getRequest();




        @Override
        public void onApplicationEvent(AuthenticationSuccessEvent a) {
            

    //        System.out.println("+=+=+=+=+=+=+: " + httpServletRequest.getHeader());

        }


    }

标签: javaspringspring-mvc

解决方案


推荐阅读