Search code examples
javaspring-mvcpojo

How does spring map post data to POJO?


I have a spring controller defined like this:

@Controller
@RequestMapping("/user")
class UserController {
    ...
    @RequestMapping(method=RequestMethod.POST)
    public String save(User user) {
        // Do something with user
        return "redirect:/...";
    }
}

How is post data (data submitted from a form) mapped to the User object in this case? Is there any documentation on how this works?

What happens if I have two POJOs like this?

@Controller
@RequestMapping("/user")
class UserController {
    ...
    @RequestMapping(method=RequestMethod.POST)
    public String save(User user, Foo anotherPojo) {
        // Do something with user
        return "redirect:/...";
    }
}

Solution

  • In the first case, Spring MVC will attempt to match the HTTP POST parameter names to the property names of the User class, converting the types of those parameters values as necessary.

    In the second case, I believe Spring will throw an exception, since it will only accept one Command object.