代码之家  ›  专栏  ›  技术社区  ›  Leonel

Spring:如何将httpservletrequest注入到请求范围的bean中?

  •  85
  • Leonel  · 技术社区  · 14 年前

    我想建立一个 request-scoped bean 在施普灵河。

    我已经成功地设置了它,所以每个请求创建一次bean。现在,它需要访问httpservletrequest对象。

    因为bean是每个请求创建一次的,所以我认为容器可以轻松地将请求对象注入到bean中。我该怎么做?

    2 回复  |  直到 14 年前
        1
  •  93
  •   skaffman    14 年前

    请求范围的bean可以与请求对象自动连接。

    private @Autowired HttpServletRequest request;
    
        2
  •  119
  •   samitgaur    14 年前

    春天暴露电流 HttpServletRequest 对象(以及当前 HttpSession 对象)通过 包装器 类型对象 ServletRequestAttributes . 此包装对象绑定到ThreadLocal,并通过调用 static 方法 RequestContextHolder.currentRequestAttributes() .

    servletrequestattributes(servletrequestattributes) 提供方法 getRequest() 要获取当前请求, getSession() 获取当前会话和其他方法,以获取存储在两个作用域中的属性。下面的代码虽然有点难看,但应该可以在应用程序的任何位置获得当前请求对象:

    HttpServletRequest curRequest = 
    ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
    .getRequest();
    

    请注意 RequestContextHolder.CurrentRequestAttributes()。 方法返回接口,需要将其类型转换为 servletrequestattributes(servletrequestattributes) 实现接口的。


    春季JavaDoc: RequestContextHolder γ ServletRequestAttributes