Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3 MVC accessing HttpRequest from controller

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?

like image 791
JBoy Avatar asked Dec 14 '11 12:12

JBoy


People also ask

Can we use REST controller in Spring MVC?

Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.


1 Answers

Spring MVC will give you the HttpRequest if you just add it to your controller method signature:

For instance:

/**  * 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(...);  } 

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.

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.

like image 86
jjmontes Avatar answered Sep 18 '22 06:09

jjmontes