Spring @ControllerAdvice 註解

  1. 經過@ControllerAdvice註解能夠將對於控制器的全局配置放在同一個位置。
  2. 註解了@Controller的類的方法能夠使用@ExceptionHandler、@InitBinder、@ModelAttribute註解到方法上。
  3. @ControllerAdvice註解將做用在全部註解了@RequestMapping的控制器的方法上
  4. @ExceptionHandler:用於全局處理控制器裏的異常。
  5. @InitBinder:用來設置WebDataBinder,用於自動綁定前臺請求參數到Model中。
  6. @ModelAttribute:原本做用是綁定鍵值對到Model中,此處讓全局的@RequestMapping都能得到在此處設置的鍵值對。
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Kevin
 * @description
 * @date 2016/7/4
 */
@ControllerAdvice
public class DemoHandlerAdvice {
    // 定義全局異常處理,value屬性能夠過濾攔截條件,此處攔截全部的Exception
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception exception, WebRequest request) {
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("errorMessage", exception.getMessage());
        return mv;
    }

    // 此處將鍵值對添加到全局,註解了@RequestMapping的方法均可以得到此鍵值對
    @ModelAttribute
    public void addAttributes(Model model){
        model.addAttribute("msg","額外的信息");
    }

    // 此處僅演示忽略request中的參數id
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder.setDisallowedFields("id");
    }
}

控制器java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Kevin
 * @description
 * @date 2016/7/4
 */
@Controller
public class DemoController {
    
    @RequestMapping("/advice")
    public String advice(@ModelAttribute("msg") String msg) throws Exception {
        throw new Exception("參數錯誤" + msg);
    }
}

控制器中拋出的異常將被自定義全局異常捕獲,並返回至error頁面。web

相關文章
相關標籤/搜索