如何在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());
}
}
2条答案
按热度按时间vc9ivgsu1#
您不应该在方面中自动连接httpservletrequest,因为这将使方面仅对从正在执行的httpservletrequest中调用的类可运行。
相反,当您需要请求时,使用requestcontextholder来获取请求。
https://stackoverflow.com/a/24029989/11985558
bt1cpqcv2#
你能试试这个吗
您还需要在web.xml文件中添加/注册requestcontextlistener侦听器。