Search code examples
javajsonspringspring-mvcmodelattribute

Accessing JSON on server using @ModelAttribute("myobject") on spring framework


I have made an spring Crud I am sending form data via post method it is working fine. my controller code:

@RequestMapping(value = "/submitobject", method = RequestMethod.POST)
public String saveOrUpdateHrEmployee(@ModelAttribute("myObjectForm") @Validated MyObject myObject,
        BindingResult result, Model model, final RedirectAttributes redirectAttributes) 

{
.
.
.    
}

But now I want to send form data in JSON, but it is not working. What should I do. I am new to spring and can't understand that how it is making the object of my bean class and getting data from parameters.Need help please Thanks in advance.


Solution

  • @RequestMapping(value = "/submitobject", method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public MyObject saveOrUpdateHrEmployee(@RequestBody @Validated MyObject myObject,
        BindingResult result, Model model, final RedirectAttributes redirectAttributes) 
    
    {
    .
    .
    .    
    }
    

    The above code will work.Let me know for any issues.Spring @RequestBody will convert MyObject into JSON.

    The simplest way for my understanding is, the @ModelAttribute will take a query string. so, all the data are being pass to the server through the url.

    As for @RequestBody, all the data will be pass to the server through a full JSON body.