SpringMVC 中 @ControllerAdvice的兩種應用
1. 異常處理 @ExceptionHandler
1.1 全局異常處理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handlerException(Exception ex) {
ex.printStackTrace();
return new Result(false, StatusCode.ERROR, ex.getMessage());
}
}
1.2 指定Controller捕獲異常處理
@ControllerAdvice(assignableTypes = AsynController.class)
1.3 捕獲自定義異常
/*
todo 自定義一個異常類,也能進行異常常處理
*/
@ExceptionHandler(value = UserNotFoundException.class)
@ResponseBody
public Map<String, Object> handlerUserNotFoundException(UserNotFoundException ex) {
ex.printStackTrace();
Map<String, Object> result = new HashMap<>();
return result;
}
2. 統一管理Model屬性 @ModelAttribute
把 Request
中的 Cookies
設置到Model
中,方便管理,也方便以後重構Controller。
@ControllerAdvice(assignableTypes = AsynController.class)
public class ModelAttributeHandler {
@ModelAttribute("token")
public String token(@RequestHeader("token") String token){
return token;
}
@ModelAttribute("jsessionId")
public String sessionId(@CookieValue("JSESSIONID") String sessionId){
return sessionId;
}
}
值得注意的是
@RequestMapping(value = "/helloWorld.do")
@ModelAttribute("attributeName")
public String helloWorld() {
return "hi";
}
如果@RequestMapping
和 @ModelAttribute
同級,返回的就不再是一個視圖名,而是Model的value,視圖名會解析成helloworld
@InitBinder 相關
解決兩個實體屬性名相同的情況,映射的時候用前綴區分,解決方案參考一下鏈接
更多 @InitBinder 與 @ControllerAdvice 的用法