异常处理器
如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。
异常处理思路
系统的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文章来源:https://www.toymoban.com/news/detail-813516.html
@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里面定义超链接文章来源地址https://www.toymoban.com/news/detail-813516.html
<a href="/account/findAccount14">异常处理器</a>
到了这里,关于Spring MVC 异常处理器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!