注解 @ControllerAdvice 的 3 种用法

1、处理全局异常

比如,上传文件大小超出限制时,使用 @ControllerAdvice 处理这异常。

如下:

@ControllerAdvice // 处理全局异常的注解
public class MyCustomException {
   @ExceptionHandler(MaxUploadSizeExceededException.class)
    public void myexception(MaxUploadSizeExceededException e, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write("上传大小超出限制!");
        out.flush();
        out.close();
    }

2、预设全局数据

比如:

@ControllerAdvice
public class GlobalData {
    @ModelAttribute
    public Map<String, Object> mydata(){
        Map<String, Object> map = new HashMap<>();
        map.put("name","you");
        map.put("address", "www.you.com");
        return map;
    }
}

3、请求参数预处理

比如:

@ControllerAdvice
public class GlobalData {
    @InitBinder("a")
    public void initA(WebDataBinder binder){
        binder.setFieldDefaultPrefix("a.");
    }

    @InitBinder("b")
    public void initB(WebDataBinder binder){
        binder.setFieldDefaultPrefix("b.");
    }
}

每天学习一点点,每天进步一点点。

posted @ 2020-06-24 10:09  爱吃西瓜的番茄酱  阅读(599)  评论(0编辑  收藏  举报