sj23
sj23

Reputation: 61

Having @RequestBody and HttpServletRequest in the same Controller method

I have a situation where i have to update the request before i process it. basically, I will have to update the request with a property which can change with time. It is not practical to ask the consumer send the property along with request.. So, I feel like the only way to do it is.. update the request in controller method before processing it..

@RequestMapping(value="/**", method=RequestMethod.POST)
public void processRequest(HttpServletRequest servletRequest, HttpServletResponse response )

Untill now, HttpServletRequest is used in the controller method. the request is then read as stream and then converted to json string to get processed. I am thinking to replace it with @RequestBody and have the request read into a pojo, then update, then process. But, I also need the pathInfo from HttpServletRequest to identify which uri i need to process the request for..

So, Can i use both @RequestBody and HttpServletRequest in the same method?? I tried it and i dint see any issues.. But, I wanted to check if there is any thing i am missing..

@RequestMapping(value="/**", method=RequestMethod.POST)
public void processRequest(@RequestBody final DateRequest request, HttpServletRequest servletRequest, HttpServletResponse response )

Please advise..

Upvotes: 6

Views: 6384

Answers (1)

Todd
Todd

Reputation: 31710

This is fine and supported by Spring. As a matter of fact, I just finished writing a controller method virtually identical to the one you use in your example. Spring is very flexible with what is allowed for a method decorated with @RequestMapping. According to the documentation:

@RequestMapping handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values. ... The table below shows supported controller method arguments.

[ See documentation for complete table ]

In the table of acceptable argument types, it specifically allows HttpServletRequest, HttpServletResponse, and objects annotated with @RequestBody.

So you should be set, according to your findings, the fact that other people are doing this, and the documentation specifically mentioning it.

Upvotes: 6

Related Questions