首先 @ControllerAdvice 增强型控制器,主要用来处理全局数据,一般搭配@ExceptionHandler、@ModelAttribute、@InitBinder 使用 有如下三个作用:
全局异常处理添加全局数据请求参数预处理1. 全局异常处理
@ControllerAdvice 最常见的使用场景就是全局异常处理,可以结合@ExceptionHandler定义全局异常捕获机制,实例代码如下:
自定义 GlobalExceptionHandler.java
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ArithmeticException.class) public void arithmeticException(ArithmeticException e, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset-utf-8"); PrintWriter out = response.getWriter(); out.write(e.getMessage().toString()); System.out.println("算术运算错误!"); out.flush(); out.close(); } @ExceptionHandler(IndexOutOfBoundsException.class) public void indexOutOfBoundsException(IndexOutOfBoundsException e, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset-utf-8"); PrintWriter out = response.getWriter(); out.write(e.getMessage().toString()); System.out.println("数组下标索引越界!"); out.flush(); out.close(); } }测试类: ExceptionController.java
@RestController public class ExceptionController { @GetMapping("/getArithmeticException") public Integer getArithmeticException() { int a = 6/0; return a; } @GetMapping("/getEIndexOutOfBoundsException") public Integer getException() { List<Integer> list = new ArrayList<Integer>(); for(int i = 0;i < 5; i++) { list.add(i); } return list.get(6); } }访问 : http://localhost:8093/getEIndexOutOfBoundsException 和 http://localhost:8093/getArithmeticException 会返回响应的错误信息!
当然,@ExceptionHandler这里也直接指明为Exception,代码如下:
@ExceptionHandler(Exception.class) public void arithmeticException(Exception e, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset-utf-8"); PrintWriter out = response.getWriter(); out.write(e.getMessage().toString()); System.out.println("出现错误》》》》》》》》!"); out.flush(); out.close(); }2.添加全局数据
@ControllerAdvice 可以结合 @ModelAttribute定义全局数据,代码如下:
@ControllerAdvice public class GlobalDataConfig { @ModelAttribute(value = "dept") public Map<String, String> deptInfo(){ Map<String, String> map = new HashMap<String, String>(); map.put("id", "D00001"); map.put("name", "物联网人工智能产品部"); map.put("address", "广州"); return map; } }注:这里 @ModelAttribute(value = “dept”) 相当于一个键,返回的map相当于值,总体类似于一个map集合
测试代码:
@GetMapping("/getModelInf") public String getModelInf(Model model){ Map<String, Object> map = model.asMap(); return map.toString(); }结果: 从结果看它也类似于一个map集合!
3. 请求参数预处理 暂时还没有完全理解透彻,待定…
