java - 在 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());
}
}
解决方案
推荐阅读
- wordpress - 搜索页面上的 Wordpress ACF 中继器字段
- types - 在 Elm 中使用数字作为类型
- php - 值出现两次,同时在 php 的选择下拉列表中限制相同的值
- java - 计算 ArrayList< 的所有唯一组合
> 在 Java 中具有所需长度 n - json - 通过 PowerShell 访问 JSON 数组
- ios - 崩溃 - 共享应用程序扩展 - 图像 - iOS 13 - EXC_RESOURCE RESOURCE_TYPE_MEMORY(限制=120 MB,未使用=0x0)
- machine-learning - 总结 ML 中的词嵌入向量会破坏它们的含义吗?
- javascript - ASP .net 核心端点配置
- java - 杰克逊无法读取超类中声明的字段
- sql - 获取月份和年初至今的水平份额(价值、数量)。份额公式 - 比较/行业