024 SpringMvc的异常处理
一:说明
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的异常处理的更多相关文章
- SpringMVC 全局异常处理
在 JavaEE 项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理.每个过程都单独处理异常,系统的代码耦合度 ...
- springmvc 中异常处理
springmvc 中异常处理常见三种处理方式: 1:SimpleMappingExceptionResolver处理的是处理器方法里面出现的异常 2 3.自定义异常处理器:处理的是处理器方法里面出现 ...
- springMvc全局异常处理
本文中只测试了:实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器 对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提 ...
- 012医疗项目-模块一:统一异常处理器的设计思路及其实现(涉及到了Springmvc的异常处理流程)
我们上一篇文章是建立了一个自定义的异常类,来代替了原始的Exception类.在Serice层抛出异常,然后要在Action层捕获这个异常,这样的话在每个Action中都要有try{}catch{}代 ...
- springMVC对异常处理的支持
无论做什么项目,进行异常处理都是非常有必要的,而且你不能把一些只有程序员才能看懂的错误代码抛给用户去看,所以这时候进行统一的异常处理,展现一个比较友好的错误页面就显得很有必要了.跟其他MVC框架一样, ...
- 【Spring】18、springMVC对异常处理的支持
无论做什么项目,进行异常处理都是非常有必要的,而且你不能把一些只有程序员才能看懂的错误代码抛给用户去看,所以这时候进行统一的异常处理,展现一个比较友好的错误页面就显得很有必要了.跟其他MVC框架一样, ...
- 【Spring】SpringMVC之异常处理
java中的异常分为两类,一种是运行时异常,一种是非运行时异常.在JavaSE中,运行时异常都是通过try{}catch{}捕获的,这种只能捕获显示的异常,通常项目上抛出的异常都是不可预见.那么我们能 ...
- Java springmvc 统一异常处理的方案
前言:为什么要统一异常处理?经常在项目中需要统一处理异常,将异常封装转给前端.也有时需要在项目中统一处理异常后,记录异常日志,做一下统一处理. Springmvc 异常统一处理的方式有三种. 一.使用 ...
- 一起学SpringMVC之异常处理
在系统开发过程中,异常处理是不可避免,如果异常处理不好,会给用户造成很差的体验,本文主要讲解在SpringMVC开发过程中,异常处理的相关知识点,仅供学习分享使用,如有不足之处,还请指正. 概述 在S ...
随机推荐
- DCNN models
r egion based RNN Fast RCNN Faster RCNN F-RCN Faster RCNN the first five layers is same as the ZF ne ...
- LeetCode -Reverse Pairs
my solution: class Solution { public: int reversePairs(vector<int>& nums) { int length=num ...
- VS中空项目、win32项目、控制台程序的区别(转)
空项目,大多数想单纯创建c++工程的新同学,打开vs后很可能不知道选择创建什么工程,这时候请相信我,空项目是你最好的选择.因为空工程不包含任何的源代码文件,接下来你只需要在相应的源代码文件夹和头文件文 ...
- Python中crypto模块进行AES加密和解密
#coding: utf8 import sys from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex class p ...
- 【洛谷P1896【SCOI2005】】互不侵犯King
题目描述 在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案.国王能攻击到它上下左右,以及左上左下右上右下八个方向上附近的各一个格子,共8个格子. 输入输出格式 输入格式: 只有一行,包 ...
- 第15月第6天 ios UIScrollView不能响应TouchesBegin
1. 1:@property MyScrollView *scrollView; 2:给MyScrollView,增加类别:MyScrollView+Touch 3:在类别里实现下面三个方法: @im ...
- Navicat Premium连接各种数据库
版本信息 Navicat Premium 是一套数据库开发工具,让你从单一应用程序中同时连接 MySQL.MariaDB.SQL Server.Oracle.PostgreSQL 和 SQLite 数 ...
- Django学习手册 - cookie / session
cookie """ cookie属性: obj.set_cookie(key,value,....) obj.set_signed_cookie(key,value,s ...
- Android ROM资源文件存放位置
位于目录:framework/core/res/res /frameworks/base/core/res/res/values/public.xml 上面的文件中公开了上层(也就是第三方应用或者系统 ...
- Mean shift
转载:http://blog.csdn.net/google19890102/article/details/51030884 然后引入opencv中的pyrMeanShiftFiltering函数: ...