如何在SpringMVC中获取httpservletrequest?

cygmwpex  于 2021-10-10  发布在  Java
关注(0)|答案(2)|浏览(402)

如何在SpringMVC中获取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());

        }

    }
vc9ivgsu

vc9ivgsu1#

您不应该在方面中自动连接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

bt1cpqcv

bt1cpqcv2#

你能试试这个吗

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>

相关问题