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:/...";
}
}
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.
In many occasions it should be enough if the POST parameter names are the same as you POJO attribute names. The proper way though is to use the Spring form taglib 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:
// e.g 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 your user has an address property), I don't think Spring will accept more than one command object though.
精彩评论