spring mvc处理异常
译者说明:不同浏览器运行效果不同,在Eclipse的浏览器中就没效果。建议用chrome.
这个帖子描述spring mvc3处理异常的另类技术。源码在github的spring-mvc-error-handling目录下。它是以带注释的sprimg mvc的例子为基础的。
spring3之前如何处理异常
在spring3之前,异常是用HandlerExceptionResolvers来处理的。这个接口定义的一个方法:
ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex)
注意它返回了一个ModelAndView对象。因此,碰到异常意味着被定向到一个特别的页面。然而,这种方法不适合REST Ajax访问JSONs.在这种情况下,我们并不想返回一个页面,而只是想返回一个http状态码。下面就描述一种可行的解决方案。
为了本例,设计了2个假的异常:CustmoziedException1和CustomizedException2.为了把这2个异常映射到视图,我们仍然可以使用SimpleMappingExceptionResolver.
SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {SimpleMappingExceptionResolver result= new SimpleMappingExceptionResolver();// Setting customized exception mappingsProperties p = new Properties();p.put(CustomizedException1.class.getName(), "Errors/Exception1");result.setExceptionMappings(p);// Un-mapped exceptions will be directed thereresult.setDefaultErrorView("Errors/Default");// Setting a default HTTP status coderesult.setDefaultStatusCode(HttpStatus.BAD_REQUEST.value());return result;}
我们把CustomizedException1映射到Errors/Exception1 jsp页面(视图).我们同样为没有映射的异常设置了一个默认错误页面,在此例中就是CusomizedException2.我们同样设置了默认的http状态码。
下面是Exeption1 jsp页面。默认页面与此相似。
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html;" charset=UTF-8"><title>Welcome To Exception I !!!</title>
</head>
<body><h1>Welcome To Exception I !!!</h1>Exception special message:<br/><br/>${exception.specialMsg}<br /><br/><a href="<c:url value='/'/>">Home</a>
</body>
</html>
为触发这些异常,我们创建一个假的异常控制器:
@Controller
public class TriggeringErrorsController {@RequestMapping(value = "/throwCustomizedException1")public ModelAndView throwCustomizedException1(HttpServletRequest request,HttpServletResponse response)throws CustomizedException1 {throw new CustomizedException1("Houston, we have a problem!");} @RequestMapping(value = "/throwCustomizedException2")public ModelAndView throwCustomizedException2(HttpServletRequest request,HttpServletResponse response)throws CustomizedException2 {throw new CustomizedException2("Something happened on the way to heaven!");}@ExceptionHandler(Customized4ExceptionHandler.class)@ResponseStatus(value=HttpStatus.BAD_REQUEST) @ResponseBodypublic String handleCustomized4Exception(Customized4ExceptionHandler ex) {return ex.getSpecialMsg();}@RequestMapping(value = "/throwCustomized4ExceptionHandler")public ModelAndView throwCustomized4ExceptionHandler(HttpServletRequest request,HttpServletResponse response)throws Customized4ExceptionHandler {throw new Customized4ExceptionHandler("S.O.S !!!!");} }
在spring3之前,你必须在web.xml中把SimpleMappingExceptionResolver声明成@Bean,我们用HandlerExceptionResolverComposite,后面对此将有所描述。
在web.xml中,我们配置一个http状态吗目标页面,这是处理这种问题的另一种方法。
译者注:访问http://localhost:8080/sprErrorHand/piaji.html就可以调用该页面。
<error-page><error-code>404</error-code><location>/WEB-INF/pages/Errors/My404.jsp</location></error-page>
spring 3.x以来有什么新特性?
@ResponseStatus这个注释是一个新方法,用来设置一个http状态吗,当被注释的方法被调用时。这些都由ResponseStatusExceptionResolver来处理。@ExceptionHandler注释用来在spring中方便地处理异常。这些注释被AnnotationMethodHandlerExeptionResolver来处理。
下面代码表明这些注释如何被用来设置http状态码,当一个自定义的异常被触发时。这条信息会返回到响应的正文中。
@ExceptionHandler(Customized4ExceptionHandler.class)@ResponseStatus(value=HttpStatus.BAD_REQUEST) @ResponseBodypublic String handleCustomized4Exception(Customized4ExceptionHandler ex) {return ex.getSpecialMsg();}@RequestMapping(value = "/throwCustomized4ExceptionHandler")public ModelAndView throwCustomized4ExceptionHandler(HttpServletRequest request,HttpServletResponse response)throws Customized4ExceptionHandler {throw new Customized4ExceptionHandler("S.O.S !!!!");}
在用户端这边,如果用Ajax调用,错误信息可以用下面JQuery代码:
var prefix = "/spring-mvc-error-handling";var ExceptionHandler = function() {$.ajax({type: 'GET',url: prefix + "/throwCustomized4ExceptionHandler",dataType: 'json',async: true,success: function(result) {alert('Unexpected success !!!');},error: function(jqXHR, textStatus, errorThrown) {alert(jqXHR.status + " " + jqXHR.responseText);}});}
有些人喜欢用Ajax返回一个JSON对象,带有错误码和某种信息来处理异常。我觉得没必要这样。一个简单的带有信息的错误码使得它很简单。
因为我们用了几个resolver,我们需要一个综合的resolver:
@BeanHandlerExceptionResolverComposite getHandlerExceptionResolverComposite() {HandlerExceptionResolverComposite result= new HandlerExceptionResolverComposite();List<HandlerExceptionResolver> l= new ArrayList<HandlerExceptionResolver>();l.add(new AnnotationMethodHandlerExceptionResolver());l.add(new ResponseStatusExceptionResolver());l.add(getSimpleMappingExceptionResolver());l.add(new DefaultHandlerExceptionResolver());result.setExceptionResolvers(l);return result;}
DefaultHandlerExceptionResolver处理标准的spring异常并把它们翻译成相应的http状态码。
程序运行截图(chrome中)
原文:http://technotes.tostaky.biz/2012/11/spring-mvc-error-handling.html
github:https://github.com/JVerstry/Web-Related-Examples
源代码:http://pan.baidu.com/share/link?shareid=590269867&uk=3878681452
spring mvc处理异常相关推荐
- Spring MVC全局异常后返回JSON异常数据
Spring MVC全局异常后返回JSON异常数据 参考文章: (1)Spring MVC全局异常后返回JSON异常数据 (2)https://www.cnblogs.com/exmyth/p/560 ...
- Spring MVC报异常:org.springframework.web.util.NestedServletException: Request processing failed
Spring MVC报异常:org.springframework.web.util.NestedServletException: Request processing failed 参考文章: ( ...
- Spring MVC BindingResult异常
Spring MVC BindingResult异常 参考文章: (1)Spring MVC BindingResult异常 (2)https://www.cnblogs.com/yanghuahui ...
- Spring MVC的异常处理器
异常处理器 异常处理思路 Java 中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试等手段减少运行时异常的发生. ...
- Spring MVC 处理异常的3种方式
三种方式 @ExceptionHandler标注的方法被定义为处理指定类型异常: @ResponseStatus标注的方法执行,会修改响应头中的状态码: Spring会把@ControllerAdvi ...
- Spring MVC异常统一处理(异常信息的国际化,日志记录)
JAVA EE项目中,不管是对底层的数据操作,还是业务层的处理过程,还是控制层的处理,都不可避免的会遇到各种可预知的(业务异常主动抛出).不可预知的异常需要处理.一般dao层.service层的异常都 ...
- Spring Boot Spring MVC 异常处理的N种方法
默认行为 根据Spring Boot官方文档的说法: For machine clients it will produce a JSON response with details of the e ...
- 使用Spring MVC统一异常处理实战
原文:http://blog.csdn.net/ufo2910628/article/details/40399539 1 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处 ...
- Spring MVC重定向和转发及异常处理
SpringMVC核心技术---转发和重定向 当处理器对请求处理完毕后,向其他资源进行跳转时,有两种跳转方式:请求转发与重定向.而根据要跳转的资源类型,又可分为两类:跳转到页面与跳转到其他处理器. 对 ...
最新文章
- 警告:failed to load the sqljdbc_auth.dll cause no sqljdbc_auth in java.library.path
- C. 防止E-mail注入
- scikit_learn中fit()/transform()/fit_transform()区别和联系
- 邻接矩阵实现图的深度优先搜索(1)
- 写在《ASP.NET MVC 4 Web 编程》即将出版之际!献给有节操的程序员!
- 今天终于完成对postfix配置的修改
- 数据库设计指南[整理]
- 与孩子一起学编程15章
- stm32固件库手册使用方法
- 卷积神经网络工作原理
- 室外宽温1口千兆光纤收发器工业导轨式发送机接收机单模单纤单电口
- 思岚S2激光雷达3—ROS node and test application for RPLIDAR
- java中apache和tomcat的区别和联系
- 谷歌论文Weight Agnostic Neural Networks(WANN)权重无关神经网络
- 微信读书增长策略:“无限卡会员业务”
- 下载Nexus老版本war包
- Unity【Dynamic Bone】- 关于人物模型头发、衣物等细节的处理
- 数据分析报告流程展现
- 速卖通按关键字搜索商品
- gulp之ES6转ES5
热门文章
- oracle已经创建表空间不存在,oracle表空间的创建、删除、查看、表空间不存在、及修改默认表空间详解...
- RBGA8888转nv21
- in和exist区别
- 滨江学院c语言期中考试试题,南信大滨江学院linux期末作业.doc
- 苏州公安第一次用计算机,苏州破获首起非法控制计算机信息系统程序案
- win7打开计算机 多窗口,win7电脑无法在一个窗口中打开多个文件夹怎么办?
- zj-layout组件的布局
- [Unity学习笔记:FPS游戏制作(1)]角色的移动,旋转与推进上升————(2021.6.13学习笔记)
- 小米Android 13 应用适配指南公告
- 小说更新太慢怎么办_小说:圣墟(挺好看的一部小说,现在更新非常慢)