3.4.6 @ModelAttribute 注解 Mod lAttribut 通常作用在 Controller 的某个方法上,此方法会首先被调用,
井将方法 结果作为 Model 的属性 然后再调用对应的 Controller 处理方法。
@ModelAttribute
public void findUserByid (@PathVariable Long id, Model model ) {
model . addAttribute (”user”, userService . getUserByid(id));
}
@GetMapping(path = ” /{ id)/get . json”)
@ResponseBody
public Str ng getUser (Model model) {
System. out .println (model . containsAttri bute (” use r ”) ) ;
return ” success”;
}
对于 HTTP 的请求 mod lat ibute t. on 会先调用 findUserByld 方法取得 user 并添 加到模型里。
使用 Mode!Attribute 通常可以用来向一个 Controller 中需要的公共模型添加数据。
如果 findUserByid 仅仅添加一个对象到 Model ,则可以改写成如下形式
@ModelAttribute
public User findUserByid(@PathVariab l e Long id) {
return userService . getUserByid(id) ;
}
这样 返回的对象自动添加到 Model 中,相当于调用 model.addA ribute(user)
Controller 中用注解@InitBind 声明一个方法,来自 己扩展绑定的特性,
比如:
@Controller public class MyFormController {
@InitBinder
protected void in tBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter (” yyyy- MM-dd” ))
};
@ResponseBody
@RequestMapping (” / date ” ) public void printDate(Date d ) {
System.out printl (d)
return;
}
当需要绑定到一 Date 类型的时候,如上述代码所示, 采用“归号y-MM-dd ”格式,比 如用户访 databind/date 2010-1-1 必须一这种类型访问才行