Spring mvc中@ModelAttribute和@ControllerAdvice使用

@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)造器實例

注解可配置項

  1. 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)注解,作用類似

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末张咳,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子似舵,更是在濱河造成了極大的恐慌脚猾,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件砚哗,死亡現(xiàn)場離奇詭異龙助,居然都是意外死亡,警方通過查閱死者的電腦和手機频祝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門泌参,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人常空,你說我怎么就攤上這事沽一。” “怎么了漓糙?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵铣缠,是天一觀的道長。 經(jīng)常有香客問我,道長蝗蛙,這世上最難降的妖魔是什么蝇庭? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮捡硅,結(jié)果婚禮上哮内,老公的妹妹穿的比我還像新娘。我一直安慰自己壮韭,他們只是感情好北发,可當我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著喷屋,像睡著了一般琳拨。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上屯曹,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天狱庇,我揣著相機與錄音,去河邊找鬼恶耽。 笑死密任,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的偷俭。 我是一名探鬼主播批什,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼社搅!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起乳规,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤形葬,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后暮的,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體笙以,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年冻辩,在試婚紗的時候發(fā)現(xiàn)自己被綠了猖腕。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡恨闪,死狀恐怖倘感,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情咙咽,我是刑警寧澤老玛,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響蜡豹,放射性物質(zhì)發(fā)生泄漏麸粮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一镜廉、第九天 我趴在偏房一處隱蔽的房頂上張望弄诲。 院中可真熱鬧,春花似錦娇唯、人聲如沸齐遵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽洛搀。三九已至,卻和暖如春佑淀,著一層夾襖步出監(jiān)牢的瞬間留美,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工伸刃, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留谎砾,地道東北人。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓捧颅,卻偏偏與公主長得像景图,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子碉哑,可洞房花燭夜當晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容