十一、异常处理器
当出现指定的异常时,跳转指定页面
1、基于配置的异常处理
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver
SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props>
<prop key="java.lang.ArithmeticException">error</prop> </props> </property>
<property name="exceptionAttribute" value="ex"></property> </bean>
|
2、基于注解的异常处理
1 2 3 4 5 6 7 8 9 10 11 12
| @ControllerAdvice public class ExceptionController {
@ExceptionHandler(ArithmeticException.class) public String handleArithmeticException(Exception ex, Model model){ model.addAttribute("ex", ex); return "error"; } }
|