spring map如何post数据到POJO?
我有一个这样定义的 spring 控制器:
@Controller
@RequestMapping("/user")
class UserController {
...
@RequestMapping(method=RequestMethod.POST)
public String save(User user) {
// Do something with user
return "redirect:/...";
}
}
在这种情况下,发布数据(从表单提交的数据)如何映射到 User 对象?有任何关于其工作原理的文档吗?
如果我有两个这样的 POJO 会怎样?
@Controller
@RequestMapping("/user")
class UserController {
...
@RequestMapping(method=RequestMethod.POST)
public String save(User user, Foo anotherPojo) {
// Do something with user
return "redirect:/...";
}
}
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:/...";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一种情况下,Spring MVC 将尝试将 HTTP POST 参数名称与 User 类的属性名称进行匹配,并根据需要转换这些参数值的类型。
在第二种情况下,我相信 Spring 会抛出异常,因为它只接受一个 Command 对象。
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.
在许多情况下,如果 POST 参数名称与 POJO 属性名称相同就足够了。正确的方法是使用 Spring 表单taglib 并将其绑定到您的pojo:
然后在您的JSP中:
您可以嵌套您的属性(例如,如果您的用户有地址属性,则为address.street),我认为Spring不会接受多个命令对象尽管。
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:
And then in your JSP:
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.