49

我正在使用 Spring 注释,我可以将HttpRequestContextController 传递给 Service。

我正在寻找一种静态方式或任何比传递更好的解决方案RequestContext

4

6 回答 6

109

如果您使用的是弹簧,您可以执行以下操作:

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;
}
于 2014-10-12T09:10:44.993 回答
24

或者java8方式

public static Optional<HttpServletRequest> getCurrentHttpRequest() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
        .filter(ServletRequestAttributes.class::isInstance)
        .map(ServletRequestAttributes.class::cast)
        .map(ServletRequestAttributes::getRequest);
}
于 2019-01-24T14:41:53.143 回答
4

作为参考,这将是 Kotlin 的方式:

    val currentRequest: HttpServletRequest?
        get() = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)?.request
于 2020-07-05T09:52:26.640 回答
4

作为对“或 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);
    }
于 2020-08-17T14:21:39.853 回答
3

我知道,这已经是答案了。我想标记为新更新。我们可以HttpServletRequest使用@Autowired. 它在springboot.

@Autowired
private HttpServletRequest httpServletRequest;
于 2021-09-21T18:56:56.317 回答
-1

这对我有用:

HttpServletRequest request = 
    ((ServletRequestAttributes) Objects.requireNonNull(
        RequestContextHolder.getRequestAttributes()))
    .getRequest();
于 2021-03-11T11:17:30.483 回答