一:说明

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. C# 使用ffmpeg视频截图

    <appSettings> <add key="ffmpeg" value="E:\ffmpeg\ffmpeg-20141012-git-20df026 ...

  2. JavaJavaScript之内存与变量初始化

    0.搞清三个概念:预加载与执行期:js变量存储(栈区与堆区):js变量的类型(引用类型(对象)与基本数据类型); JS在预编译时,对于函数的预加载方面,浏览器仅仅选择编译声明式函数(function ...

  3. 第16月第24天 find iconv sublime utf-8

    1. find . -type f -exec echo {} \; find src -type f -exec sh -c "iconv -f GB18030 -t UTF8 {} &g ...

  4. mongodb系列~关于双活状态的mongodb集群

    一简介:说说我们异地双活的集群 二 背景:需要建立异地双活的架构 三 构建 1 需要保证第二机房至少两个副本集DB,这样在第一机房挂掉后才能保证第二机房的可用性 2 集群状态下第二机房启用config ...

  5. maven私服内容补充

    1.添加阿里云中央仓库 注意Download Remote Indexes选项为True 1.登陆nexus私服(默认账号密码:admin/admin123) 2.点击右侧Repositories 3 ...

  6. LOJ 3093: 洛谷 P5323: 「BJOI2019」光线

    题目传送门:LOJ #3093. 题意简述: 有 \(n\) 面玻璃,第 \(i\) 面的透光率为 \(a\),反射率为 \(b\). 问把这 \(n\) 面玻璃按顺序叠在一起后,\(n\) 层玻璃的 ...

  7. Majority Element(169) && Majority Element II(229)

    寻找多数元素这一问题主要运用了:Majority Vote Alogrithm(最大投票算法)1.Majority Element 1)description Given an array of si ...

  8. centos 命令和

    一.远程工具 Window系统上 Linux 远程登录客户端有SecureCRT, Putty, SSH Secure Shell.TightVNC... 重点推荐一款 FinallShell,一般人 ...

  9. eclipse总是自动跳到ThreadPoolExecutor解决办法

    出现这种状况是因为Eclipse默认开启挂起未捕获的异常(Suspend execution on uncaught exceptions),只要关闭此项就可以了. 解决方法:在eclipse中选择W ...

  10. git命令行提交并且同步到远程代码库

    远程代码库以github为例 1.打开 git bash 2.进入项目目录 cd /e/myGitProjects/test 3.提交到本地git仓库 git add -Agit commit -m ...