springMVC05-异常处理器
在 SpringMVC 中,异常处理是一个非常重要的功能,它可以让你优雅地处理程序抛出的各种异常,向用户展示友好的提示,而不是显示一堆报错信息(如 500 页面)。
一、SpringMVC的异常处理器
返回的是ModelAndView,意味着,可以在遇到指定异常的时候,跳转到指定的页面。
二、SpringMVC 异常处理器的二种方式
3-1、基于配置的异常处理器
示例1:
在springMVC.xml中配置异常处理器
<!-- 配置异常处理器 --><bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><!-- 算数异常,跳转到error.html页面 --><prop key="java.lang.ArithmeticException">error</prop></props></property></bean>
编写测试类:
@RequestMapping("/testException")public String testException(){System.out.println(1/0);return "success";}
示例2:在error页面打印异常信息
<!-- 配置异常处理器 --><bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><!-- 算数异常,跳转到error.html页面 --><prop key="java.lang.ArithmeticException">error</prop></props></property><!-- 想要在error.html页面打印异常信息 --><!-- 异常信息默认存储在请求域中,key就是我们自定义的ex,直接在error.html页面,用这个key,输出异常信息 --><property name="exceptionAttribute" value="ex"></property></bean>
<body><h1>ArithmeticException error</h1><p th:text="${ex}"></p>
</body>
【注意】:
<property name="xxxx">,里面的name的值是固定的!
3-2、基于注解的异常处理
示例:
@ControllerAdvice其实就是@Controller的扩展注解!