启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 被 @RequestMapping 注解的方法上。
@ModelAttribute:在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取
package com.example.elasticsearch.demo.aspect;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyControllerAdvice {
/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
System.out.println("----------initBinder----------");
}
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
* @param model
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "Magical Sam");
}
/**
* 全局异常捕捉处理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg", ex.getMessage());
return map;
}
@ResponseBody
@ExceptionHandler(value = ArithmeticException.class)
public Map errorHandler1(ArithmeticException ex) {
Map map = new HashMap();
map.put("code", 200);
map.put("msg", ex.getMessage());
return map;
}
}
@RestController
@RequestMapping("/elastic")
public class BlogController {
@GetMapping("/home1")
public void home1(@ModelAttribute("author") String author) {
int a = 1/0;
// int a = 999999999*999999999;
System.out.println(author);
}
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 300);
map.put("msg", ex.getMessage());
return map;
}
@ResponseBody
@ExceptionHandler(value = ArithmeticException.class)
public Map errorHandler1(ArithmeticException ex) {
Map map = new HashMap();
map.put("code", 400);
map.put("msg", ex.getMessage());
return map;
}
}