【问题标题】:Spring MVC - Can I autowire HttpServletRequest in RestControllerSpring MVC - 我可以在 RestController 中自动装配 HttpServletRequest
【发布时间】:2018-09-15 18:25:37
【问题描述】:

我可以像下面那样在我的RestController 中自动连接HttpServletRequest,即使它在高度并发的环境中执行,它是否会返回不同的servletRequest。我有一个不能作为方法参数的限制,因为我正在实现一个自动生成的接口,并且不会将HttpServletRequest 作为方法参数。

@RestController
public class MyController implements MyInterface {
        
    @Autowired
    private HttpServletRequest servletRequest;
        
    @Override
    @RequestMapping(value = "/test", produces = {"application/json"}, consumes = {"application/json"}, method = RequestMethod.POST)
    public ResponseEntity<MyResponse> test(@RequestBody final MyRequest payload){
        ...
    }
    ...
}

我已经阅读了这些 SO 问题和其他一些关于此的文章。但只是想确保当我们在控制器中自动连接 HttpServletRequest 时,它的 ScopeRequest

Spring 3 MVC accessing HttpRequest from controller

How are Threads allocated to handle Servlet request?

Scope of a Spring-Controller and its instance-variables

How do I get a HttpServletRequest in my spring beans?

How To Get HTTP Request Header In Java


注意:我确实尝试过,它似乎工作正常。但只是想确认即使在高度并发的环境中它也是一个万无一失的解决方案。 此外,如果这是正确的方法,如果有人能解释它是如何工作的,我将不胜感激。

【问题讨论】:

  • 为什么不public ResponseEntity&lt;MyResponse&gt; test(@RequestBody final MyRequest payload, HttpServletRequest request) {...}? Spring不会自动注入请求吗?
  • 我确实在我的问题中提到我不能这样做。因为我需要在我的RestController 中实现MyInterface,它是从规范自动生成的,它不能将HttpServletRequest 作为方法参数。

标签: spring-mvc scope httprequest


【解决方案1】:

我用过这个,效果很好。但不幸的是,我没有找到任何官方文档提到这应该有效。

这是基于我通过运行具有不同标头/有效负载等的多个请求来调试代码的理解的解释:

无论我们是在字段上还是通过构造函数自动装配,servletRequest 就像一个代理对象,它将调用委托给 Current HttpServletRequest,每个请求都不同。因此,即使它是通过 Singleton RestController 中的构造函数注入的,它仍然会将调用委托给每个新请求的相应 HttpServletRequest。这利用AutowireUtils.ObjectFactoryDelegatingInvocationHandler 访问当前的HttpServletRequest 对象。它的 java 文档还说 Reflective InvocationHandler 用于延迟访问 当前目标对象

因此,即使自动装配的 Proxy 对象对于所有请求始终相同,调用委托的底层目标对象是当前的 HttpServletRequest 对象,它是每个请求的对象。


还有另一种获取HttpServletRequest 的方法是使用RequestContextHolder,如this answer 中所述

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

注意:因为这个解释是基于我的理解,如果有人有的话,请分享任何官方文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-22
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2014-07-26
    • 2013-01-29
    • 2015-03-17
    相关资源
    最近更新 更多