我正在使用 Spring 注释,我可以将HttpRequestContext
Controller 传递给 Service。
我正在寻找一种静态方式或任何比传递更好的解决方案RequestContext
。
如果您使用的是弹簧,您可以执行以下操作:
public static HttpServletRequest getCurrentHttpRequest(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
return request;
}
logger.debug("Not called in the context of an HTTP request");
return null;
}
或者java8方式
public static Optional<HttpServletRequest> getCurrentHttpRequest() {
return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
.filter(ServletRequestAttributes.class::isInstance)
.map(ServletRequestAttributes.class::cast)
.map(ServletRequestAttributes::getRequest);
}
作为参考,这将是 Kotlin 的方式:
val currentRequest: HttpServletRequest?
get() = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)?.request
作为对“或 Java 8 方式”上面的@andrebrait 评论的回应,这些方法出现在ServletRequestAttributes.class
public static Optional<HttpServletRequest> getCurrentHttpRequest() {
return
Optional.ofNullable(
RequestContextHolder.getRequestAttributes()
)
.filter(ServletRequestAttributes.class::isInstance)
.map(ServletRequestAttributes.class::cast)
.map(ServletRequestAttributes::getRequest);
}
我知道,这已经是答案了。我想标记为新更新。我们可以HttpServletRequest
使用@Autowired
. 它在springboot
.
@Autowired
private HttpServletRequest httpServletRequest;
这对我有用:
HttpServletRequest request =
((ServletRequestAttributes) Objects.requireNonNull(
RequestContextHolder.getRequestAttributes()))
.getRequest();