Java Spring:如何将 HttpServletRequest 注入请求范围的 bean?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3320674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:05:45  来源:igfitidea点击:

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

javaspringservlets

提问by Leonel

I'm trying to set up a request-scoped beanin Spring.

我正在尝试在 Spring 中设置一个请求范围的 bean

I've successfully set it up so the bean is created once per request. Now, it needs to access the HttpServletRequest object.

我已经成功设置了它,因此每个请求都会创建一次 bean。现在,它需要访问 HttpServletRequest 对象。

Since the bean is created once per request, I figure the container can easily inject the request object in my bean. How can I do that ?

由于每个请求都会创建一次 bean,我认为容器可以轻松地将请求对象注入到我的 bean 中。我怎样才能做到这一点 ?

采纳答案by skaffman

Request-scoped beans can be autowired with the request object.

请求范围的 bean 可以与请求对象自动装配。

private @Autowired HttpServletRequest request;

回答by samitgaur

Spring exposes the current HttpServletRequestobject (as well as the current HttpSessionobject) through a wrapperobject of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the staticmethod RequestContextHolder.currentRequestAttributes().

Spring通过类型为 的包装器对象公开当前HttpServletRequest对象(以及当前HttpSession对象)。该包装器对象绑定到 ThreadLocal 并通过调用方法获得。ServletRequestAttributesstaticRequestContextHolder.currentRequestAttributes()

ServletRequestAttributesprovides the method getRequest()to get the current request, getSession()to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

ServletRequestAttributes提供getRequest()获取当前请求、getSession()获取当前会话的方法以及获取存储在两个范围中的属性的其他方法。下面的代码虽然有点难看,但应该能让你在应用程序的任何地方获取当前的请求对象:

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

Note that the RequestContextHolder.currentRequestAttributes()method returns an interface and needs to be typecasted to ServletRequestAttributesthat implements the interface.

请注意,该RequestContextHolder.currentRequestAttributes()方法返回一个接口,需要将其类型转换为ServletRequestAttributes实现该接口的类型。



Spring Javadoc:RequestContextHolder| ServletRequestAttributes

Spring Javadoc:RequestContextHolder| ServletRequestAttributes

回答by Will Cain

As suggested hereyou can also inject the HttpServletRequestas a method param, e.g.:

正如此处所建议的您还可以将 注入HttpServletRequest作为方法参数,例如:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}