java - 如何在 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());
}
}
解决方案
你能试试这个
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>
推荐阅读
- mysql - 如何在多个连接中将 mysql 查询转换为 ruby on rails 活动记录
- html - 在CSS中旋转-90度后对齐菜单项
- php - TYPO3,realurl 在更改域后不起作用
- python - 从 .log/.txt 文件创建列 - python
- javascript - 根据一天中的时间更改对象的值?
- c++ - std::optional & compilers - 这不应该崩溃吗?
- ios - 在基于 swift 的 ios 框架中创建可自定义/可覆盖的 localizable.strings 文件
- excel - 根据单元格值删除范围中的行
- unix - 如何在ansible中将用户分配给组?
- react-native - 用 jest + 酶测试 react-native-navigation wix