使用 @ModelAttribute 作为参考数据 - 避免绑定

发布于 2024-10-25 20:55:31 字数 1014 浏览 2 评论 0原文

我想使用 @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() 中使用自动装配参数。假设 PetPerson 都有一个成员 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

装迷糊 2024-11-01 20:55:31

我认为你做错了,在这种情况下 @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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文