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)开发者_StackOverflow中文版{
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?
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.
精彩评论