问题描述
我想自己处理请求和会话属性,而不是将它留给 spring @SessionAttributes
,例如用于登录 cookie 处理.
I would like to handle request and session attributes myself rather then leave it to spring @SessionAttributes
, for login of cookies handling for example.
我只是不知道如何从控制器中访问 HttpRequest
,我需要一种方法来访问 @RequestAttribute
之上的层并访问 >HttpRequest
本身.使用 Stripes 通过实现一个 ApplicationContext
并调用 getAttribute()
来做到这一点.
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()
.
此外,将 HttpServletRequest
作为参数传递似乎不起作用:
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.
您对此有什么建议吗?
推荐答案
Spring MVC 会给你 HttpRequest 如果你只是将它添加到你的控制器方法签名中:
Spring MVC will give you the HttpRequest if you just add it to your controller method signature:
例如:
/**
* Generate a PDF report...
*/
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
@PathVariable("objectId") Long objectId,
HttpServletRequest request,
HttpServletResponse response) {
// ...
// Here you can use the request and response objects like:
// response.setContentType("application/pdf");
// response.getOutputStream().write(...);
}
如您所见,只需将 HttpServletRequest
和 HttpServletResponse
对象添加到签名中,Spring MVC 就可以将这些对象传递给您的控制器方法.您也需要 HttpSession
对象.
As you see, simply adding the HttpServletRequest
and HttpServletResponse
objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession
object too.
似乎 HttpServletRequest/Response 不适用于 Spring 3 下的某些人.尝试使用 Eduardo Zola 指出的 Spring WebRequest/WebResponse 对象.
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.
我强烈建议您查看 受支持参数列表 Spring MVC 能够自动神奇地注入到您的处理程序方法中.
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.
这篇关于Spring 3 MVC 从控制器访问 HttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2