【问题标题】:Accessing HttpServletRequest object in a normal Java class from Spring从 Spring 访问普通 Java 类中的 HttpServletRequest 对象
【发布时间】:2012-04-03 18:42:36
【问题描述】:

我在 Spring MVC 3.06 Web 应用程序中有一个普通的 Java 类。

在这个类中,我想在一个方法中注入或获取HttpServletRequest 对象。

我知道我可以传递这个,但我想知道如何在不将请求传递给方法的情况下获取请求。也许使用注释或类似的?

此外,以这种方式获取请求的“真正”问题是什么,除了一些人认为它是丑陋的编码。我的意思是,这样访问不稳定吗?

最好是非应用服务器依赖的方式。

见过

(HttpServletRequest) RequestContextHolder.getRequestContext().getExternalContext().getNativeRequest() 

但这似乎不适用于 Spring MVC 3.06 。 RequestContextHolder 没有方法 getRequestContext()

【问题讨论】:

    标签: java servlets spring-mvc


    【解决方案1】:

    使用

    ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    

    我不确定你从哪里得到RequestContextHolder.getRequestContext(),这是完全错误的。

    这样访问不稳定吗?

    不,它足够稳定,假设您始终将代码作为HttpServlet 请求线程的一部分运行。主要问题是,是的,它很丑陋,而且它使您的代码难以测试。这就是不使用它的充分理由。

    如果您必须使用它,则将其与您的代码解耦,例如

    public void doSomething() {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        doSomething(request);
    }
    
    void doSomething(HttpServletRequest request) {
       // put your business logic here, and test this method
    }
    

    【讨论】:

    • 谢谢,是的,也许这可能会在测试时产生问题,最有可能是在测试控制器和操作时。那时解耦并没有真正的帮助,但我添加了一个静态 getRequest 方法,该方法调用默认实现(上面),可以覆盖。谢谢!
    • 这工作到现在都很好:( ...我正在尝试使用 RequestContextHolder 从视图中访问
    • @Anthony 您可以将响应对象存储在调度程序或拦截器中
    【解决方案2】:

    @Context HttpServletRequest httpServletRequest =null;

    使用这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      相关资源
      最近更新 更多