Spring 3 MVC 从控制器访问 HttpRequest
我想自己处理请求和会话属性,而不是将其留给 spring @SessionAttributes
,例如用于 cookie 处理的登录。
我只是不知道如何从控制器内访问 HttpRequest
,我需要一种方法来访问 @RequestAttribute
之上的一层并访问 HttpRequest< /代码>本身。 Stripes 用于通过实现
ApplicationContext
并调用 getAttribute()
来实现此目的。
另外,将 HttpServletRequest 作为参数传递似乎不起作用:
@RequestMapping(value="/") public String home(HttpServletRequest request){
System.out.println(""+request.getSession().getCreationTime());
return "home";
}
上述方法不会打印任何内容。
您对此有什么建议吗?
I would like to handle request and session attributes myself rather then leave it to spring @SessionAttributes
, for login of cookies handling for example.
I just cant figure out how could I access the HttpRequest
from within a controller, I need a way to go a layer above the @RequestAttribute
and access the HttpRequest
itself. With Stripes in used to do this by implementing an ApplicationContext
and calling getAttribute()
.
Also, passing the HttpServletRequest
as parameter seems not to be working:
@RequestMapping(value="/") public String home(HttpServletRequest request){
System.out.println(""+request.getSession().getCreationTime());
return "home";
}
The above method does not print anything.
Do you have any advice on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只需将 HttpRequest 添加到控制器方法签名中,Spring MVC 就会为您提供 HttpRequest:
例如:
如您所见,只需将 HttpServletRequest 和 HttpServletResponse 对象添加到签名即可Spring MVC 将这些对象传递给您的控制器方法。您还需要
HttpSession
对象。编辑:似乎 HttpServletRequest/Response 对于 Spring 3 下的某些人不起作用。尝试使用 Spring WebRequest/WebResponse 对象,正如 Eduardo Zola 指出的那样。
我强烈建议您查看 Spring MVC 能够自动神奇地注入到您的处理程序方法中的支持参数列表。
Spring MVC will give you the HttpRequest if you just add it to your controller method signature:
For instance:
As you see, simply adding the
HttpServletRequest
andHttpServletResponse
objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want theHttpSession
object too.EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.
I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.
我知道这是一个老问题,但是...
您也可以在您的类中使用它:
这将提供
HttpServletRequest
的当前实例,供您在您的方法中使用。I know that is a old question, but...
You can also use this in your class:
And this will provide the current instance of
HttpServletRequest
for you use on your method.另一种方法是使用
RequestContextHolder
,例如:(自:2.0)RequestContextHolder Holder 类以线程绑定的 RequestAttributes 对象的形式公开 Web 请求。如果可继承标志设置为 true,则当前线程生成的任何子线程都会继承该请求。
Another way is to use
RequestContextHolder
like: (Since: 2.0)RequestContextHolder Holder class to expose the web request in the form of a thread-bound RequestAttributes object. The request will be inherited by any child threads spawned by the current thread if the inheritable flag is set to true.