How does spring display mail data in POJO?

I have a spring controller defined as follows:

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

How, in this case, data is compared with data (data from the form) mapped to the User object? Is there any documentation on how this works?

What happens if I have two POJOs?

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

In the first case, Spring MVC will try to match the HTTP POST parameter names with the properties of the User class, converting the types of these parameter values ​​if necessary.

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

+2
source

In many cases, this should be sufficient if the POST parameter names match the POJO attribute names. The correct way is to use the Spring taglib form and bind it to your pojo:

 @Controller @RequestMapping("/user") class UserController { ... @RequestMapping(value="/login", method=RequestMethod.GET) public ModelAndView get() { return new ModelAndView().addObject("formBackingObject", new User()); } @RequestMapping(value="/login", method=RequestMethod.POST) public String save(User user) { // Do something with user return "redirect:/..."; } } 

And then in your JSP:

 // eg in user/login.jsp <form:form method="post" commandName="formBackingObject" action="/user/login.html"> <form:label path="username"><spring:message code="label.username" /></form:label> <form:input path="username" cssErrorClass="error" /> <form:label path="password"><spring:message code="label.password" /></form:label> <form:password path="password" cssErrorClass="error" /> <p><input class="button" type="submit" value="<spring:message code="label.login" />"/></p> </form:form> 

You can nest your attributes (e.g. address.street if the user has an address property), I don't think Spring will accept more than one command object.

+2
source

Source: https://habr.com/ru/post/1310112/


All Articles