一般使用第二种方法去实现全局异常
SimpleMappingExceptionResolver实现全局异常,这种情况主要是处理视图的异常。
在servlet-context.xml中配置对象
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--
页面在转发时出现异常,设置默认的错误页面,value指向error.jsp页面
-->
<property name="defaultErrorView" value="error"></property>
<!--
发送错误时,设置错误变量名,在jsp中可以通过EL表达式获取错误的具体形式
${ex}
-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
</beans>
error.jsp的代码:
<%--
Created by IntelliJ IDEA.
User: zks
Date: 2/4/2022
Time: 5:50 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
默认的错误页面:${ex}
</body>
</html>
也可以为自定义的异常配置专门的页面,如图下面key的值就是对应的自定义异常,后面那个params_error就是对应的自定义异常。
第二种实现方式:实现接口:HandlerExceptionResolver,并且实现其中的方法。ParamsException异常为自定义参数异常,这里先判断,然后mv.setViewName(“params_error”)(这里的params_error为jsp包中的一个jsp文件)。mv.addObjection(“ex”,pe.geMsg)这里把异常信息添加到ex中。