SpringMVC中的异常处理

异常处理概述
  1) Spring MVC 通过 HandlerExceptionResolver  处理程序的异常,包括 Handler 映射、数据绑定以及目标方法执行时发生的异常。
  2) SpringMVC 提供的 HandlerExceptionResolver 的实现类

默认异常处理_DefaultHandlerExceptionResolver

1)对一些特殊的异常进行处理,比如:
 NoSuchRequestHandlingMethodException、
 HttpRequestMethodNotSupportedException、
 HttpMediaTypeNotSupportedException、
 HttpMediaTypeNotAcceptableException等。出现异常交给DefaultHandlerExceptionResolver处理

异常处理  SimpleMappingExceptionResolver

1)如果希望对所有异常进行统一处理,可以使用 SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常。

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.NullPointerException">error</prop>
            </props>
        </property>
    </bean>

  发生异常时,会自动显示视图解析器地址下的error.jsp。并且配置异常解析器:自动将异常对象信息,存放到request范围内,名为exception。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <a href="#">操作异常,请稍后重试</a>
    ${exception }  
    
</body>
</html>
 
 
 
 
原文地址:https://www.cnblogs.com/lemonzhang/p/12940192.html