Reputation: 5064
I have a plain Spring MVC controller that returns a Model and View. This works great. But now we are moving over to pure REST architecture where the server only communicates via JSON.
Instead of revamping everything, I am trying to resuse the existing controllers as much as i could and here is what i am able to do
I am able to reuse the GET requests to same controllers by including a ContentNegotiatingViewResolver. So now the same controller can return a jsp and a model converted into json based on accept header.
Now the other part is POST requests that i need some help on.
To bind a json request I ll have to use @RequestBody on the existing controllers but I want to do it conditionally in the same way as i did for GET requests. So if the accept header is json it should use that message converter to bind the model otherwise use the usual html form binding.
And after this is done, how to handle BindingResult object for my scenario?
To summarize here are my questions:
Upvotes: 0
Views: 1919
Reputation: 49095
To handle the POST requests you will need to have a custom AbstractHttpMessageConverter
and a ModelAttributeMethodProcessor
.
You need the MessageConverter to handle the controllers that do use request body (@RequestBody
) and the ModelAttributeMethodProcessor to handle the validation if the controller is using request parameters (@RequestParam
).
Obviously you'll want to check for a header or something otherwise do the default binding.
I answered a different question about validating immutable objects but the same method applies.
Upvotes: 0
Reputation: 1300
Look into the consumes
and produces
attributes of the @RequestMapping
attribute. You could have two versions of the same method with different consume
s, one of which can take a @RequestBody
and one that doesn't.
Can't really help you with the second part of your question, sorry.
Upvotes: 1