controllerAdvice

在spring 3.2中,新增了@ControllerAdvice 註解,可以用於定義@ExceptionHandler、@InitBinder、@ModelAttribute,並應用到所有@RequestMapping中。參考:@ControllerAdvice 文檔
例子:

/**
 * controller 增強器
 */
@ControllerAdvice
public class DemoControllerAdvice {

    /**
     * 應用到所有@RequestMapping註解方法,在其執行之前初始化數據綁定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {}

    /**
     * 把值綁定到Model中,使全局@RequestMapping可以獲取到該值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }

    /**
     * 全局異常捕捉處理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", 500);
        map.put("msg", ex.getMessage());
        return map;
    }

}

啓動應用後,被 @ExceptionHandler、@InitBinder、@ModelAttribute 註解的方法,都會作用在 被 @RequestMapping 註解的方法上。
@ModelAttribute:在Model上設置的值,對於所有被 @RequestMapping 註解的方法中,都可以通過 ModelMap 獲取,如下:

@RequestMapping("/home")
public String home(ModelMap modelMap) {
    System.out.println(modelMap.get("author"));
}

//或者 通過@ModelAttribute獲取
@RequestMapping("/home")
public String home(@ModelAttribute("author") String author) {
    System.out.println(author);
}

@ExceptionHandler 攔截了異常,我們可以通過該註解實現自定義異常處理。其中,@ExceptionHandler 配置的 value 指定需要攔截的異常類型,上面攔截了 Exception.class 這種異常。
如果不需要返回json數據,而要渲染某個頁面模板返回給瀏覽器

@ExceptionHandler(value = Exception.class)
public ModelAndView myErrorHandler(Exception ex) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("error");
    modelAndView.addObject("code", ex.getCode());
    modelAndView.addObject("msg", ex.getMsg());
    return modelAndView;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章