Spring 3 MVC从控制器访问HttpRequest [英] Spring 3 MVC accessing HttpRequest from controller

查看:114
本文介绍了Spring 3 MVC从控制器访问HttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自己处理请求和会话属性,而不是将其留给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.

您对此有何建议?

推荐答案

如果将MHttp添加到控制器方法签名中,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(...);

}

如您所见,只需将HttpServletRequestHttpServletResponse对象添加到签名中,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.

在Spring 3下,HttpServletRequest/Response对于某些人似乎不起作用.正如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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆