首页 > 其他 > 详细

09 ControllerAdvice的使用

时间:2020-03-23 21:02:56      阅读:70      评论:0      收藏:0      [点我收藏+]

ControllerAdvice就是Controller的Advice,即Controller的强化或者横切,说的更确切一些就是其他Controller在执行之前,一定会先执行配置了ControllerAdvice的Controller。它不仅能做异常处理,还能做数据的格式化以及数据绑定。

1、前提约束

2、操作步骤

  • 在src文件夹下创建net.wanho.controller.TheController.java,内容如下:
@ControllerAdvice
public class TheController{
    @ExceptionHandler(value = ArithmeticException.class)
    public String exception()
    {
        System.out.println("监控所有Controller,任意Controller产生数学异常,都会进到这里");
        return "arithmetic";
    }

    @ModelAttribute(value = "message")
    public String modelAttribute()
    {
        return "全局消息,任意Controller都会获取到";
    }

    @InitBinder
    public void timeFormat(WebDataBinder binder) {
        System.out.println("所有的Controller的时间格式化都会进到这里处理");
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }
}
  • 在src文件夹下创建net.wanho.controller.TestTheController.java,内容如下:
    @Controller
    public class TestTheController{
    @RequestMapping("/advice/exception")
    @ResponseBody
    public String testException()
    {
    System.out.println(1/0);
    return "exception";
    }

    @RequestMapping("/advice/modelattribute")
    @ResponseBody
    public String testException(@ModelAttribute("message") String message)
    {
    return message;
    }

    @RequestMapping("/advice/timeformat")
    @ResponseBody
    public String testException(Date date)
    {
    return date.toString();
    }
    }

  • 启动tomcat,在浏览器中分别输入以下url:

测试异常:http://localhost:8080/advice/exception
测试数据绑定:http://localhost:8080/advice/modelattribute
测试日期格式化:http://localhost:8080/advice/timeformat

以上就是ControllerAdvice横切到任意Controller的使用。

09 ControllerAdvice的使用

原文:https://www.cnblogs.com/alichengxuyuan/p/12554629.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!