@ModelAttribute在一个方法 [英] @ModelAttribute in a method
问题描述
想象一下这样的代码:
@RequestMapping(value="/users", method=RequestMethod.GET)
public String list(Model model) {
...
}
@InitBinder("user")
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("password"); // Don't allow user to override the value
}
@ModelAttribute("user")
public User prepareUser(@RequestParam("username") String username){
...
}
@RequestMapping(value="/user/save", method=RequestMethod.POST)
public String save(@ModelAttribute("user") User user, Model model) {
...
}
我使用一个初始化绑定,以避免一个字段可以绑定,我标记一个方法(prepareUser())与@ModelAttribute,以准备我的用户对象绑定之前。所以当我调用/ user / save initBinder()和prepareUser()被执行时。
I use an init binder to avoid that a field can be binded and I mark a method (prepareUser()) with @ModelAttribute to prepare my User object before it is binded. So when I invoke /user/save initBinder() and prepareUser() are executed.
我已经在@InitBinder和@ModelAttribute中设置了user,所以Spring-MVC可以理解,这种方法应该只在使用@ModelAttribute(user)执行方法之前应用。
I have set "user" in both @InitBinder and @ModelAttribute so Spring-MVC could understand that this methods should only be applied before executing a method with @ModelAttribute("user").
问题是,使用@ModelAttribute(user )在此控制器的每个映射方法之前执行。例如,如果我调用/用户prepareUser在list()方法之前执行。如何使这个准备工作只在save()方法之前执行,所有方法都在同一个控制器中?
The problem is that the method annotated with @ModelAttribute("user") is executed before every mapped method of this controller. For example if I invoke /users prepareUser is executed before list() method. How can I make that this preparer is only executed before save() method having all the methods in the same controller?
谢谢
推荐答案
这不是真正的 @ModelAttribute
。如果使用它作为一个方法参数,它将注释的参数放入模型中(没关系)。如果你把它放在一个方法上,那么每次都会调用控制器中每个方法都可以访问的参考数据。
That's not really what @ModelAttribute
is for. If you use it as a method parameter, it puts the annotated parameter into the model (that's fine). If you put it on a method, it's called every time to provide reference data that every method in the controller should have access to.
如果你想控制建筑物您的用户对象,您有几个选项。对我来说最明显的是:
If you want to take control of building up your User object, you have several options. The two that are most obvious to me are:
- 使用您的InitBinder方法添加一个新的自定义编辑器(PropertyEditor类),用于构建用户对象,
- 使用转换服务在Spring 3中将字符串用户名转换为用户对象。
这篇关于@ModelAttribute在一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!