1.相关概念
@Controller
public class LoginController {
@GetMapping("/index")
public String index(){
int a= 10/0; //模拟服务器出错
return "index";
}
}
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver. 其中HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver. 在不进行配置的时候, 默认使用DefaultHandlerExceptionResolver, 于是当出现异常时, 就会出现如下类型的页面.
可是这样满屏的报错信息只有程序员能看懂发生了什么事, 对于用户来说就是一脸懵逼, 而且这样的页面和网站正常页面的风格极其不搭, 实在太丑.
于是SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,可以自定义异常处理逻辑和异常跳转页面.SimpleMappingExceptionResolver的使用方式同样有两种, 一种是使用xml配置文件进行配置, 另一种是使用注解编写配置类进行配置.
2.使用xml进行配置
在xml配置文件springMVC.xml中加入如下配置
<!--自定义异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--
properties的键表示处理器方法执行过程中出现的异常
properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面
-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--
exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享
-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
自定义的异常跳转页面error.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>抱歉, 服务器出错了呀!</h1>
<p th:text="${ex}"></p>
</body>
</html>
运行测试
3.使用注解进行配置
也可以不在xml配置文件中进行配置, 我们可以使用注解的方式在配置类中进行配置, 效果是一样的.
//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
//@ExceptionHandler用于设置所标识方法处理的异常
@ExceptionHandler(ArithmeticException.class)
//ex表示当前请求处理中出现的异常对象
public String handleArithmeticException(Exception ex, Model model){
model.addAttribute("ex", ex);
return "error";
}
}
自定义的异常跳转页面error.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>抱歉, 服务器出错了呀!</h1>
<p th:text="${ex}"></p>
</body>
</html>
运行测试