Spring MVC 异常处理器

异常处理器

如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。

异常处理思路

系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:

创建异常处理器

@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
​
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                    HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", ex.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
​
}

测试

  • 编写controller

@Controller
@RequestMapping("/account")
public class AccountController {
​
   @RequestMapping("/findAccount14")
    public String findAccount14(Model model) {
        model.addAttribute("msg", "欢迎你 springmvc");
        //模拟异常信息
        int i = 10/0;
        return "success";
    }
}
  • 在index.jsp里面定义超链接

<a href="/account/findAccount14">异常处理器</a>

相关推荐

  1. SpringMVC异常处理

    2024-01-12 21:42:11       65 阅读
  2. SpringMVC异常处理

    2024-01-12 21:42:11       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-12 21:42:11       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-12 21:42:11       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-12 21:42:11       82 阅读
  4. Python语言-面向对象

    2024-01-12 21:42:11       91 阅读

热门阅读

  1. __declspec(dllexport)与__declspec(dllimport) 的区别

    2024-01-12 21:42:11       45 阅读
  2. C语言学习记录—进阶作业(通讯录静态版本)

    2024-01-12 21:42:11       54 阅读
  3. Netty Channel 详解

    2024-01-12 21:42:11       63 阅读
  4. 代码随想录算法训练营Day24|77. 组合

    2024-01-12 21:42:11       54 阅读
  5. ClickHouse中JOIN算法选择逻辑以及auto选项

    2024-01-12 21:42:11       47 阅读
  6. python之异常与日志

    2024-01-12 21:42:11       57 阅读
  7. 职工工作量统计(课程设计)

    2024-01-12 21:42:11       47 阅读
  8. Go语言中Print Printf Println的区别

    2024-01-12 21:42:11       54 阅读
  9. SQL语句

    SQL语句

    2024-01-12 21:42:11      52 阅读
  10. 在vue中使用v-for遍历arco.design图标

    2024-01-12 21:42:11       58 阅读
  11. ant-design-vue的table组件的自定义表头和表格内容

    2024-01-12 21:42:11       55 阅读
  12. flask web学习之模板(二)

    2024-01-12 21:42:11       60 阅读
  13. 原型和原型链

    2024-01-12 21:42:11       53 阅读
  14. [渗透测试学习] Crocodile - HackTheBox

    2024-01-12 21:42:11       55 阅读