【Spring】SpringMVC 中 @ControllerAdvice的两种应用

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

更多 @ModelAttribute 的用法

@InitBinder 相关

解决两个实体属性名相同的情况,映射的时候用前缀区分,解决方案参考一下链接
更多 @InitBinder 与 @ControllerAdvice 的用法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章