@ModelAttribute從代碼看红柱,可以在方法或方法參數(shù)上注解。方法為controller類中的方法贯城〖釉担可以是不帶@RequestMapping方法鸭叙。
注解在方法上
@ModelAttribute
public Account addAccount(@RequestParam String uid) {
return accountManager.findAccount(uid);
}
@ModelAttribute
public void populateModel(@RequestParam String uid, Model model) {
model.addAttribute(accountManager.findAccount(uid));
// add more ...
}
上面兩種寫法效果相同,都是將Account暴露到model中,@ModelAttribute 注解的方法只能是@Contrller標注的類或父子類中生百,每次調(diào)用@RequestMapping方法之前都會先調(diào)用@ModelAttribute递雀,一般用于獲取公共數(shù)據(jù),如獲取當前用戶信息。
注解在方法參數(shù)上
public String processSubmit(@ModelAttribute("pet") Pet pet) {
}
如果model中不存在該數(shù)據(jù),則會實例化參數(shù),然后添加到model中(省去了手動添加的步驟)蚀浆。比如示例方法中,如果model中不存在"pet"名稱的實例,則會創(chuàng)建一個同名的實例放到model中缀程。model中"pet"來源
- 可能來自于@SessionAttributes
- 可能來自于同Contrller類中的@ModelAttribute方法,如上節(jié)addAccount方法
@@RequestMapping(path = "/accounts/update/{uid}", method = RequestMethod.PUT)
public String processSubmit(@ModelAttribute("account") Account account) { }
- 可能來自于URL模板變量
@RequestMapping(path = "/accounts/{uid}", method = RequestMethod.GET)
public String save(@ModelAttribute("uid") String uid) { }
- 可能來自默認構(gòu)造器實例
注解可配置項
- name:表示在model中的名稱,如果不配置默認名稱根據(jù)參數(shù)類型和返回值類型確定
protected final void addReturnValueAsModelAttribute(Method handlerMethod, Class<?> handlerType,
Object returnValue, ExtendedModelMap implicitModel) {
ModelAttribute attr = AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class);
String attrName = (attr != null ? attr.value() : "");
if ("".equals(attrName)) {
Class<?> resolvedType = GenericTypeResolver.resolveReturnType(handlerMethod, handlerType);
attrName = Conventions.getVariableNameForReturnType(handlerMethod, resolvedType, returnValue);
}
implicitModel.addAttribute(attrName, returnValue);
}
ControllerAdvice 注解
@ModelAttribute一般解決同一個Controller中共性問題(如果放在一個公共的Contrller父類,也可以解決多Controller間共性問題),@ControllerAdvice主要解決多Contrller中的共性問題,如公共的數(shù)據(jù)市俊,全局異常處理杨凑,全局入?yún)⒊鰠⑥D(zhuǎn)換等“诿粒可包含@ExceptionHandler,@InitBinder,@ModelAttribute注解的方法撩满,這些方法默認將對所有Contrller的@RequestMapping方法啟用(可通過@ControllerAdvice屬性值限制范圍)
屬性值
basePackages、basePackageClasses绅你、assignableTypes伺帘、annotations:限定作用范圍,可配置各種類型
//包路徑限定
String[] basePackages() default {};
//包路徑解析類
Class<?>[] basePackageClasses() default {};
//直接配置Controller類或接口,如{UserController.class,ControllerInterface.class}
Class<?>[] assignableTypes() default {};
//配置指定注解標注的類,如{RestController.class,Controller.class}
Class<? extends Annotation>[] annotations() default {};
InitBinder 注解
初始化數(shù)據(jù)類型綁定
@Controller
public class MyFormController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}
// ...
}
@Controller
public class MyFormController {
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
//
}
JsonView 注解
jackson包下的實現(xiàn),可在方法忌锯、成員變量伪嫁、方法參數(shù)和注解類上使用。
@PostMapping("/get1")
@JsonView(WithoutPasswordView.class)
public User createUser(){
return new User("eric", "7!jd#h23",23);
}
@PostMapping("/get2")
@JsonView(WithPasswordView.class)
public User createUser(){
return new User("eric", "7!jd#h23",23);
}
public class User {
public interface WithoutPasswordView {};
public interface WithPasswordView extends WithoutPasswordView {};
private String username;
private String password;
private Integer age;
public User() {
}
public User(String username, String password,Integer age) {
this.username = username;
this.password = password;
this.age = age;
}
@JsonView(WithoutPasswordView.class)
public String getUsername() {
return this.username;
}
@JsonView(WithoutPasswordView.class)
public Integer getAge() {
return this.username;
}
@JsonView(WithPasswordView.class)
public String getPassword() {
return this.password;
}
}
請求/get1
返回 {"username":"eric","age":23}
請求/get2
返回 {"username":"eric","age":23,"password":"7!jd#h23"}
實現(xiàn)了根據(jù)不同接口需要返回指定數(shù)據(jù)偶垮,也可以在方法入?yún)⑹褂聾JsonView(WithPasswordView.class)注解,作用類似