Home » Java » java – Combine functionality of @ModelAttribute and @RequestBody in Spring MVC-Exceptionshub

java – Combine functionality of @ModelAttribute and @RequestBody in Spring MVC-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Consider a @PostMapping in Spring MVC, and we want to map the request body to a DTO, as well as other request parameters like query and path variables.

For mapping the request body we can use the @RequestBody annotation on a parameter, which will tell Spring to use the RequestResponseBodyMethodProcessor.

For mapping the request parameters we can use the @ModelAttribute annotation (or avoid any annotations; same effect), which will tell Spring to use the ServletModelAttributeMethodProcessor.

But is there an easy way to combine these two? Is there a way to make spring first map the DTO with request parameters and then override with data deserialized from the JSON in the body?

The only way I see it at the moment is to create a custom HandlerMethodArgumentResolver but I’d like to reuse any existing Spring functionality first.

How to&Answers: