SpringMVC异常处理

网友投稿 882 2022-11-01

SpringMVC异常处理

SpringMVC异常处理

异常处理的两种方式

#.使用SpringMVC提供的异常处理器SimpleMappingExceptionResolver#.使用Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理机制

我们先看一下不使用异常处理器的情况 1.在service层模拟异常情况(接口代码省略)

public class DemoServiceImpl implements DemoService { public void show1() { System.out.println("抛出类型转换异常...."); Object str = "zhangsan"; Integer num = (Integer)str; } public void show2() { System.out.println("抛出除零异常...."); int i = 1/0; } public void show3() throws FileNotFoundException { System.out.println("文件找不到异常...."); InputStream in = new FileInputStream("C:/xxx/xxx/xxx.txt"); } public void show4() { System.out.println("空指针异常....."); String str = null; str.length(); } public void show5() throws MyException { System.out.println("自定义异常...."); throw new MyException(); }}

2.编写Controller层

@Controllerpublic class DemoController { @Autowired private DemoService demoService; @RequestMapping(value = "/show") public String show() throws FileNotFoundException, MyException { System.out.println("show running......"); //demoService.show1(); //demoService.show2(); //demoService.show3(); //demoService.show4(); demoService.show5(); return "index"; }}

3.配置applicaitonContext.xml文件

4.配置spring-mvc.xml文件

5.启动tomcat访问

我们不可能让用户访问时看到这种页面一般的做法就是当某个程序出现异常时,让它跳转到某个jsp页面

使用SpringMVC提供的异常处理器SimpleMappingExceptionResolver

6.所以我们可以在spring-mvc.xml中加入这一段代码 defaultEroorView:当后面map集合里面的异常都不匹配时,才会执行这个默认的配置 value:代表视图,不写error.jsp是因为我在上文中已经配置了视图解析器

7.再次启动tomcat进行访问(出现异常就会帮我们跳转到错误页面)

自定义异常处理器

编写异常处理类

public class MyExceptionResolver implements HandlerExceptionResolver { /* 参数Exception:异常对象 返回值ModelAndView:跳转到错误视图信息 */ public ModelAndView resolveException(HttpServletRequest HttpServletResponse Object o, Exception e) { ModelAndView modelAndView = new ModelAndView(); if(e instanceof MyException){ modelAndView.addObject("info","自定义异常"); }else if(e instanceof ClassCastException){ modelAndView.addObject("info","类转换异常"); } modelAndView.setViewName("error"); return modelAndView; }}

2.将自定义异常处理类配置到spring-mvc.xml文件中

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Mybatis-Dao层实现(通过代理方式)
下一篇:springboot整合JPA访问Mysql的实现方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~