09 ControllerAdvice的使用
发布日期:2022-03-30 20:19:32 浏览次数:30 分类:博客文章

本文共 1502 字,大约阅读时间需要 5 分钟。

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

1、前提约束

  • 完成基于注解的springmvc的demo

2、操作步骤

  • 在src文件夹下创建net.wanho.controller.TheController.java,内容如下:
@ControllerAdvicepublic 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的使用。

转载地址:https://www.cnblogs.com/alichengxuyuan/p/12554629.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:08 数据绑定之校验
下一篇:04 静态页面的处理、转发、重定向和视图解析器

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月08日 08时28分22秒