一:说明

1.介绍

  Springmvc提供HandlerExceptionResolver处理异常,包括Handler映射,数据绑定,以及目标方法执行。

2.几个接口的实现类

  AnnotationMethodHandlerExceptionResolver

  DefaultHandlerExceptionResolver

  ResponseStatusExceptionResolver

  SimpleMappingExceptonResolver

  ExceptionHandlerExceptionResolver

  当开发的时候,如果配置了<mvc:annotation-driven>时,就默认配置了一下的实现类:

  ExceptionHandlerExceptionResolver,ResponseStatusExceptionResolver,DefaultHandlerExceptionResolver

二:ExceptionHandlerExceptionResolver

1.介绍

  

2.程序

  可以做到,出现异常,使用springmvc的注解进行处理异常。

 package com.spring.it.exception;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; @Controller
public class ExceptionHandlerDemo {
/**
*异常处理类
*/
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
System.out.println("result="+(10/i));
return "success";
} /**
* 异常的处理
*/
@ExceptionHandler({ArithmeticException.class})
public String handlerArithmeticException(Exception ex) {
System.out.println("come a exception:"+ex);
return "error";
} }

3.error.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Error page</h3>
</body>
</html>

4.效果

  

5.页面显示异常的方式

  @ExceptionHandler方法的入参中不能传入Map,若是希望将异常的信息导入到页面,需要使用ModelAndView方法作为返回值。

 package com.spring.it.exception;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
public class ExceptionHandlerDemo {
/**
*异常处理类
*/
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
System.out.println("result="+(10/i));
return "success";
} /**
* 异常的处理
*/
@ExceptionHandler({ArithmeticException.class})
public ModelAndView handlerArithmeticException(Exception ex) {
System.out.println("come a exception:"+ex);
ModelAndView mv=new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
} }

6.error。jsp

  获取异常信息

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Error page</h3>
${exception }
</body>
</html>

7.效果

  

8.优先级

  如果出现多个异常的处理方法,走哪一个方法呢?

  是找与异常匹配度更高的处理异常方法。

9.@ControllerAdvice

  如果在当前的@ExceptionHandler处理当前方法出现的异常,则去由@ControllerAdvice标记的类中查找@ExceptionHandler标记的方法

结构:

  

ExceptionHandlerDemo:

 package com.spring.it.exception;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
public class ExceptionHandlerDemo {
/**
*异常处理类
*/
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
System.out.println("result="+(10/i));
return "success";
} }

HandlerException:

 package com.spring.it.exception;

 import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView; @ControllerAdvice
public class HandlerException {
/**
* 异常的处理
*/
@ExceptionHandler({ArithmeticException.class})
public ModelAndView handlerArithmeticException(Exception ex) {
System.out.println("come a exception:"+ex);
ModelAndView mv=new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
} }

三:ResponseStatusExceptionResolvler

1.介绍

  

2.@ResponseStatus注解的类

 package com.spring.it.exception;

 import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户名与密码不匹配")
public class UserNameNotMatchPasswordException extends RuntimeException{
private static final long serialVersionUID=1L;
}

3.处理异常类

 package com.spring.it.exception;

 import org.apache.tomcat.util.buf.UEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
public class ExceptionHandlerDemo {
/**
*异常处理类,test ExceptionHandlerExceptionResolver
*/
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
System.out.println("result="+(10/i));
return "success";
} /**
*异常处理类,test ExceptionHandlerExceptionResolver
*/
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i) {
if(i==12) {
throw new UserNameNotMatchPasswordException();
}else {
System.out.println("conmmon execute");
}
return "success";
} }

4.效果

  

四:DefaultHandlerExceptionResolver

1.介绍

  

五:SimpleMappingExceptionResolver

1.介绍

  

2.处理类

 package com.spring.it.exception;

 import org.apache.tomcat.util.buf.UEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
public class ExceptionHandlerDemo {
/**
*异常处理类,test ExceptionHandlerExceptionResolver
*/
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
System.out.println("result="+(10/i));
return "success";
} /**
*异常处理类,test ExceptionHandlerExceptionResolver
*/
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i) {
if(i==12) {
throw new UserNameNotMatchPasswordException();
}else {
System.out.println("conmmon execute");
}
return "success";
} /**
*异常处理类,test ExceptionHandlerExceptionResolver
*/
@RequestMapping("/testSimpleMappingExceptionResolver")
public String testSimpleMappingExceptionResolver(@RequestParam("i") int i) {
String[] array=new String[10];
String num=array[i];
System.out.println("num:"+num);
return "success";
} }

2.效果

  

3.解决方式

  这个异常可以有SimpleMappingExceptionResolver来处理。

  在xml中注册。

  出现什么异常转到哪一个页面。

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 配置自定义扫描的包 -->
<context:component-scan base-package="com.spring.it" ></context:component-scan> <!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean> <mvc:annotation-driven></mvc:annotation-driven> <!-- 转换器 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="employeeConverter"/>
</set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <mvc:default-servlet-handler/>
<mvc:annotation-driven ignore-default-model-on-redirect="true"></mvc:annotation-driven> <!-- 国家化 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean> <!-- <mvc:view-controller path="/i18n" view-name="i18n"/> -->
<mvc:view-controller path="/i18n2" view-name="i18n2"/> <!-- 配置SessionLocaleResolver -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <mvc:interceptors>
<!-- 配置自定义拦截器 -->
<bean class="com.spring.it.interceptors.FirstInterceptor"></bean>
<!-- 配置拦截器的作用路径 -->
<mvc:interceptor>
<mvc:mapping path="/emps"/>
<bean class="com.spring.it.interceptors.SecondInterceptor"></bean>
</mvc:interceptor> <!-- 配置LocaleChangeInterceter拦截器 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors> <!-- 配置CommonsMultipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="102400"></property>
</bean> <!-- 配置SimpleMappingExceptionResolver来映射异常 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>
</beans>

4.效果

  

  在页面上可以看到异常的情况。

 

024 SpringMvc的异常处理的更多相关文章

  1. SpringMVC 全局异常处理

    在 JavaEE 项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理.每个过程都单独处理异常,系统的代码耦合度 ...

  2. springmvc 中异常处理

    springmvc 中异常处理常见三种处理方式: 1:SimpleMappingExceptionResolver处理的是处理器方法里面出现的异常 2 3.自定义异常处理器:处理的是处理器方法里面出现 ...

  3. springMvc全局异常处理

    本文中只测试了:实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器 对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提 ...

  4. 012医疗项目-模块一:统一异常处理器的设计思路及其实现(涉及到了Springmvc的异常处理流程)

    我们上一篇文章是建立了一个自定义的异常类,来代替了原始的Exception类.在Serice层抛出异常,然后要在Action层捕获这个异常,这样的话在每个Action中都要有try{}catch{}代 ...

  5. springMVC对异常处理的支持

    无论做什么项目,进行异常处理都是非常有必要的,而且你不能把一些只有程序员才能看懂的错误代码抛给用户去看,所以这时候进行统一的异常处理,展现一个比较友好的错误页面就显得很有必要了.跟其他MVC框架一样, ...

  6. 【Spring】18、springMVC对异常处理的支持

    无论做什么项目,进行异常处理都是非常有必要的,而且你不能把一些只有程序员才能看懂的错误代码抛给用户去看,所以这时候进行统一的异常处理,展现一个比较友好的错误页面就显得很有必要了.跟其他MVC框架一样, ...

  7. 【Spring】SpringMVC之异常处理

    java中的异常分为两类,一种是运行时异常,一种是非运行时异常.在JavaSE中,运行时异常都是通过try{}catch{}捕获的,这种只能捕获显示的异常,通常项目上抛出的异常都是不可预见.那么我们能 ...

  8. Java springmvc 统一异常处理的方案

    前言:为什么要统一异常处理?经常在项目中需要统一处理异常,将异常封装转给前端.也有时需要在项目中统一处理异常后,记录异常日志,做一下统一处理. Springmvc 异常统一处理的方式有三种. 一.使用 ...

  9. 一起学SpringMVC之异常处理

    在系统开发过程中,异常处理是不可避免,如果异常处理不好,会给用户造成很差的体验,本文主要讲解在SpringMVC开发过程中,异常处理的相关知识点,仅供学习分享使用,如有不足之处,还请指正. 概述 在S ...

随机推荐

  1. angularjs指令中scope参数 true、false、{} 的区别详解

    scope 有三个参数 true.false.{} scope 默认是 false,当 scope设置为true时,会从父作用域继承并创建一个新的作用域对象, 按照true .false的反向思维,我 ...

  2. Elaticsearch 集群

    elasticsearch开源的搜索引擎:  ElasticSearch 个基于Lucene的搜索服务器:可以使用多节点的备份:集群设置: (类似是个数据库型.有索引有什么的).(lucene apa ...

  3. BZOJ:1816 [Cqoi2010]扑克牌 (贪心或二分答案)

    题面 \(solution:\) 这道题难就难在你能否读懂题目的意思,我们将它翻译一下: 现在我有n根竹子(每根竹子有\(c_i\)节,每节竹子高度为1),我可以通过消耗一点法力值使某一根竹子的某两节 ...

  4. EOF \n \0 NULL 之间的区别

    \n 是换行符 \0 是字符串的结束标志 EOF是流的结束标志 FILE* 这种流 NULL 是指针为空 第一个问题是EOF  它是end of file的缩写,表示"文字流"(s ...

  5. RNN(3) ------ “blog:RNN学习之路”

    博客链接:http://blog.csdn.net/yangyangyang20092010/article/details/50374289 Recurrent Neural Network 学习之 ...

  6. 扫AR

  7. emmc基础技术8:操作模式3-interrupt mode

    1. 前言 eMMC总线操作包含: boot mode, device identification mode interrupt mode data transfer mode 本文主要描述inte ...

  8. C语言函数调用栈(三)

    6 调用栈实例分析 本节通过代码实例分析函数调用过程中栈帧的布局.形成和消亡. 6.1 栈帧的布局 示例代码如下: //StackReg.c #include <stdio.h> //获取 ...

  9. androidpn 推送系统

    (文中部分内容来自网络,如无意中侵犯了版权,请告之!) XMPP协议: XMPP : The Extensible Messaging andPresence Protocol. 中文全称:可扩展通讯 ...

  10. Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档

    1.添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!--swagger2--> <dependency> <groupId>io.spr ...