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. 請求參數預處理
暫時還沒有完全理解透徹,待定…

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