有没有静态方法可以在 Spring 中获取当前的 HttpServletRequest [英] Is there a static way to get the current HttpServletRequest in Spring

查看:21
本文介绍了有没有静态方法可以在 Spring 中获取当前的 HttpServletRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于有没有静态方法可以在 Spring 中获取当前的 HttpServletRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆