文章目录
@ControllerAdvice是对注解了@Controller注解的类进行增强。
该注解使用@Component注解,这样的话当我们使用 context:component-scan扫描时也能扫描到。
***该注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法会应用到所有的Controller类中 @RequestMapping注解的方法。
2 @ExceptionHandler
这个注解表示Controller中任何一个@RequestMapping方法发生异常,则会被注解了@ExceptionHandler的方法拦截到
使用这个注解可以进行全局的异常处理
@ControllerAdvice
public class MyControllerAdvice {
Logger logger = Logger.getLogger(MyControllerAdvice.class);
// 应用到所有@RequestMapping注解方法,在其执行之前把返回值放入ModelMap中
@ModelAttribute
public Map<String, Object> before() {
Map<String, Object> map = new HashMap<>();
map.put("name", "tom");
return map;
}
// 应用到所有【带参数】的@RequestMapping注解方法,在其执行之前初始化数据绑定器
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
// DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,
// true));
logger.info("initBinder……");
}
// 应用到所有@RequestMapping注解的方法,在其抛出指定异常时执行
@ExceptionHandler(Exception.class)
@ResponseBody
//可以返回json数据
public String handleException(Exception e) {
logger.error(e.getMessage(),e);
return e.getMessage();
}
}