1、基于配置的异常处理
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver
SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,在springMVC中的配置方式:
<!--配置异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--当出现key中的异常时,如果新建了error页面,则可以跳转到error页面-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--设置将异常信息共享在请求域中的键 可以将异常信息通过请求域展示到页面中 value中存储的是请求域中的异常信息的键-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
2、基于注解的异常处理
package com.rqs.mvc.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ExceptionController {
//{}中写的是可能会出现的异常的class
@ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
/**
*
*/
public String testException(Exception ex, Model model){
//将异常信息放入请求域中 ex是异常信息的键
//将异常信息放入请求域中 ex是异常信息的键
model.addAttribute("ex", ex);
//跳转到error页面
return "error";
}
}