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 的用法