SpringMVC 学习笔记(十) 异常处理HandlerExceptionResolver
Spring MVC 通过 HandlerExceptionResolver 处理程序的异常,包含 Handler 映射、数据绑定以及目标方法运行时发生的异常。
SpringMVC 提供的 HandlerExceptionResolver 的实现类
DispatcherServlet 默认装配的 HandlerExceptionResolver :
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTY3NDc0NTA2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
假设加入了<mvc:annotation-driven/> 则装配变为:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTY3NDc0NTA2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTY3NDc0NTA2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
1.1. ExceptionHandlerExceptionResolver
ExceptionHandlerExceptionResolver 主要处理 Handler 中用 @ExceptionHandler 注解定义的方法。
l @ExceptionHandler 注解定义的方法优先级问题:比如发生的是NullPointerException,可是声明的异常有RuntimeException 和 Exception,此候会依据异常的近期继承关系找到继承深度最浅的那个 @ExceptionHandler注解方法。即标记了 RuntimeException 的方法
l ExceptionHandlerMethodResolver 内部若找不到 @ExceptionHandler 注解的话,会找 @ControllerAdvice 中的 @ExceptionHandler 注解方法
Java:
package com.ibigsea.springmvc.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class ExceptionController { /**
* 假设运行此Controller里面的方法出现<b>数学异常</b>,则会运行该方法
* @param e
* @return
*/
@ExceptionHandler({ArithmeticException.class})
public String arithmeticException(Exception e){
System.out.println("arithmeticException:"+e);
return "error";
} /**
* 假设运行此Controller里面的方法出现异常,则会运行该方法
* @param e
* @return
*/
@ExceptionHandler({Exception.class})
public String exceptionHandle(Exception e){
System.out.println("Exception"+e);
return "error";
} @RequestMapping("/exception")
public String exception(Integer i){
System.out.println(10/i);
return "success";
} }
上述异常处理代码会优先运行arithmeticException方法.
或者在类上面加入@ControllerAdvice注解
package com.ibigsea.springmvc.controller; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice
public class TestExceptionHandler { @ExceptionHandler({ArithmeticException.class})
public String handleException(Exception e) {
System.out.println("----> 出异常了: " + e);
return "error";
} }
注意:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTY3NDc0NTA2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
由于在运行@ExceptionHandler修饰的方法时没有传入BindingAwareModelMap对象,所以不能在方法上面加入额外的形參
1.2. ResponseStatusExceptionResolver
l 在异常及异常父类中找到 @ResponseStatus 注解,然后使用这个注解的属性进行处理。
l 定义一个 @ResponseStatus 注解修饰的异常类
l 若在处理器方法中抛出了上述异常:若ExceptionHandlerExceptionResolver 不解析该异常。因为触发的异常 UnauthorizedException 带有@ResponseStatus注解。
因此会被ResponseStatusExceptionResolver 解析到。
最后响应HttpStatus.UNAUTHORIZED 代码给client。HttpStatus.UNAUTHORIZED 代表响应码401。无权限。
关于其它的响应码请參考 HttpStatus 枚举类型源代码。
Java:
@RequestMapping("/responseStatus")
public String responseStatus(Integer i){
if (i>20) {
throw new TestResponseStatusException();
}
return "success";
}
package com.ibigsea.springmvc.exceptionresolver; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value=HttpStatus.FORBIDDEN, reason="測试@ResponseStatus!")
public class TestResponseStatusException extends RuntimeException { private static final long serialVersionUID = 4566548902417978204L; }
结果:
1.3. DefaultHandlerExceptionResolver
对一些特殊的异常进行处理。比方NoSuchRequestHandlingMethodException、HttpRequestMethodNotSupportedException、HttpMediaTypeNotSupportedException、HttpMediaTypeNotAcceptableException等。
@RequestMapping(value="/defaultHandler",method=RequestMethod.POST)
public String defaultHandlerException(){
return "success";
}
1.4. SimpleMappingExceptionResolver
假设希望对全部异常进行统一处理,能够使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用相应的视图报告异常
JAVA
@RequestMapping("/simpleMapping")
public String simpleMappingException(Integer i){
String[] strs = new String[10];
System.out.println(strs[i]);
return "success";
}
Spring-mvc.xml
<!-- 配置使用SimpleMappingExceptionResolver来映射异常 -->
<bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="ex"></property>
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTY3NDc0NTA2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
SpringMVC 学习笔记(十) 异常处理HandlerExceptionResolver的更多相关文章
- springmvc学习笔记--REST API的异常处理
前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...
- 史上最全的SpringMVC学习笔记
SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...
- SpringMVC学习笔记之二(SpringMVC高级参数绑定)
一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...
- springmvc学习笔记(简介及使用)
springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...
- python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例
python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例 新浪爱彩双色球开奖数据URL:http://zst.aicai.com/ssq/openInfo/ 最终输出结果格 ...
- springmvc学习笔记---面向移动端支持REST API
前言: springmvc对注解的支持非常灵活和飘逸, 也得web编程少了以往很大一坨配置项. 另一方面移动互联网的到来, 使得REST API变得流行, 甚至成为主流. 因此我们来关注下spring ...
- WCF 学习笔记之异常处理
WCF 学习笔记之异常处理 1:WCF异常在配置文件 <configuration> <system.serviceModel> <behaviors> <s ...
- SpringMVC:学习笔记(8)——文件上传
SpringMVC--文件上传 说明: 文件上传的途径 文件上传主要有两种方式: 1.使用Apache Commons FileUpload元件. 2.利用Servlet3.0及其更高版本的内置支持. ...
- springmvc学习笔记(常用注解)
springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...
随机推荐
- jquery--延迟对象
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- vim-缓存区中打开另外一个文件的方法
现在有这么一种情况: 我现在在ubuntu用户根目录下-- 我根目录下有一个文件夹blogs,这个文件夹下面有两个文件:text1,text2. 我现在从-目录下进行如下操作 ...
- C#接口,类,集成
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- javafx drag
public class EffectTest extends Application { @Override public void start(Stage stage) { stage.setTi ...
- gSOAP 使用WebServer心得
关于正常怎么使用gSOAP的话,下面那篇博客已经讲得非常详细,我就不再赘述了 https://www.cnblogs.com/dengpeng1004/p/6165751.html 问题1: WCF ...
- 洛谷 P2837 晚餐队列安排
P2837 晚餐队列安排 题目背景 Usaco Feb08 Bronze 题目描述 为了避免餐厅过分拥挤,FJ要求奶牛们分2批就餐.每天晚饭前,奶牛们都会在餐厅前排队入内,按FJ的设想,所有第2批就餐 ...
- 智能指针shared_ptr, auto_ptr, scoped_ptr, weak_ptr总结
看这里: http://blog.csdn.net/lollipop_jin/article/details/8499530 shared_ptr可以多线程同时读,但是涉及到写,需要加锁. share ...
- 给指定的用户无需密码执行 sudo 的权限
给指定的用户无需密码执行 sudo 的权限 cat /etc/passwd 可以查看所有用户的列表 w 可以查看当前活跃的用户列表 cat /etc/group 查看用户组 cat /etc/pass ...
- system.setting-全局变量数据监听
今天在setting里添加了一个新的变量,想要实现对这个变量的监听.现在记录下方法 首先就是明白一点,我们在system.setting里添加的变量,都会被保存在data/data/com.andro ...
- BZOJ5137: [Usaco2017 Dec]Standing Out from the Herd(广义后缀自动机,Parent树)
Description Just like humans, cows often appreciate feeling they are unique in some way. Since Farme ...