否有静态方法来获取当前请求的HttpServletRequest

否有静态方法来获取当前请求的HttpServletRequest

本文介绍了是否有静态方法来获取当前请求的HttpServletRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring批注,我可以将HttpRequestContext从Controller传递到Service.

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

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

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

推荐答案

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

If you are using spring you can do the following:

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

这篇关于是否有静态方法来获取当前请求的HttpServletRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 00:25