spring 是否有静态方式获取当前请求的HttpServletRequest

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/592123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:49:33  来源:igfitidea点击:

Is there a static way to get the HttpServletRequest of the current request

springservletsrequest

提问by Spring Monkey

I am using Spring annotations, I can pass the HttpRequestContextfrom the Controller to the Service.

我正在使用 Spring 注释,我可以将HttpRequestContext控制器从控制器传递到服务。

I am looking for a static way or any better solution than passing RequestContextaround.

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

回答by Abbadon

If you are using spring you can do the following:

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

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;
}

回答by Panthro

Or the java8 way

或者java8方式

public static Optional<HttpServletRequest> getCurrentHttpRequest() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
        .filter(requestAttributes -> ServletRequestAttributes.class.isAssignableFrom(requestAttributes.getClass()))
        .map(requestAttributes -> ((ServletRequestAttributes) requestAttributes))
        .map(ServletRequestAttributes::getRequest);
}