方法中的@ModelAttribute [英] @ModelAttribute in a method

查看:29
本文介绍了方法中的@ModelAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下这样的代码:

@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) {        
    ...
}

我使用 init 绑定器来避免可以绑定字段,并使用 @ModelAttribute 标记一个方法 (prepareUser()) 以在绑定之前准备我的 User 对象.所以当我调用/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") 注释的方法在这个控制器的每个映射方法之前执行.例如,如果我调用/users 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:

  1. 使用 InitBinder 方法添加新的自定义编辑器(PropertyEditor 类)以构建用户对象,
  2. 在 Spring 3 中使用 转换服务 将字符串用户名转换为用户对象.
  1. Use your InitBinder method to add a new custom editor (a PropertyEditor class) for building User objects,
  2. Use the conversion service in Spring 3 to convert string usernames to User objects.

这篇关于方法中的@ModelAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆