使用 @ModelAttribute 作为参考数据 - 避免绑定
我想使用 @ModelAttribute
的自动装配魔法来获取和传递参考数据。这样做的问题是,使用 @ModelAttribute
添加到模型的任何内容都被假定为表单支持对象,然后绑定到请求,可能会修改对象。
我只是希望将它们添加到模型中以供视图参考,并能够使用参数级别 @ModelAttribute
将对象连接到用 @RequestMapping
注释的方法中。有没有一种方法可以在不使用一些冗长的 @InitBinder
方法的情况下完成此任务?
例如:
@ModelAttribute("owner")
public Person getOwner(@PathVariable("ownerId") Integer ownerId){
return getOwnerFromDatabaseById(ownerId);
}
@RequestMapping("/{ownerId}/addPet.do")
public ModelAndView addPet(HttpServletRequest request, @ModelAttribute("owner") Person owner){
String name = ServletRequestUtils.getStringParameter(request, "name");
Pet pet = new Pet();
pet.setName(name);
pet.setOwner(owner);
saveToDatabase(pet);
}
一个简单的例子,其中宠物被添加到主人身上。我希望将所有者放置在模型中以供视图使用,并且我还希望在 addPet()
中使用自动装配参数。假设 Pet
和 Person
都有一个成员 name
。在这种情况下,owner
将自动绑定到请求,并将其 name
设置为宠物的名称。如何避免这种情况?
I'd like to use the autowiring magic of @ModelAttribute
for obtaining and passing around reference data. The problem in doing this is that anything added to the model with @ModelAttribute
is assumed to be a form backing object and then is bound to the request, potentially modifying the objects.
I simply want them added to the model for the view's reference and to be able to use the parameter level @ModelAttribute
to wire objects into methods annotated with @RequestMapping
. Is there a way to accomplish this without some verbose @InitBinder
method?
for example:
@ModelAttribute("owner")
public Person getOwner(@PathVariable("ownerId") Integer ownerId){
return getOwnerFromDatabaseById(ownerId);
}
@RequestMapping("/{ownerId}/addPet.do")
public ModelAndView addPet(HttpServletRequest request, @ModelAttribute("owner") Person owner){
String name = ServletRequestUtils.getStringParameter(request, "name");
Pet pet = new Pet();
pet.setName(name);
pet.setOwner(owner);
saveToDatabase(pet);
}
A trivial example where a pet is added to an owner. I'd like to have the owner placed in the model to be used by the view, and i'd also like to make use of autowiring the parameter in addPet()
. Assume both Pet
and Person
have a member name
. In this case, owner
will automatically get bound to the request, setting its name
to the pet's name. How can this be avoided?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你做错了,在这种情况下 @ModelAttribute 应该是 Pet - 这就是应该用作表单支持对象的东西。要根据 OwnerId 自动填充所有者,您可以为 Owner 类注册一个属性编辑器,该编辑器将具有您当前在 getOwner 方法中拥有的逻辑。
I think you are doing it wrong, in this case the @ModelAttribute should be Pet - that is what should be used as the form backing object. To get he owner populated automatically based on the ownerId you can register a property editor for the Owner class that will have the logic you currently have in the getOwner method.