SpringBoot中@ControllerAdvice的使用

首先 @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. 请求参数预处理
暂时还没有完全理解透彻,待定…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值