1 描述 
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。 
那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。 
2 分析 
Spring MVC处理异常常见有4种方式: 
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver; 
(2)实现Spring的异常处理SimpleMappingExceptionResolver自定义自己的异常处理器;

(3)实现HandlerExceptionResolver 接口自定义异常处理器 
(4)使用注解@ExceptionHandler实现异常处理;

3 实战

一:使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

源码介绍:

1.lib包(jar包)和web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

2.index.jsp(测试页面入口)和 error.jsp(有错误则会跳到此页面)和 hello.jsp(没错误则会跳到此页面)

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>异常处理器测试</title>
</head>
<body>
<form action="frist.do" method="post">
<input type="submit" value="测试" />
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>这是错误页面</title>
</head>
<body>
这是错误页面 ${ex.message }
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>成功欢迎页面</title>
</head>
<body>
你竟然没报错<br/>
</body>
</html>

3.MyController,java(定义自己的处理器)

package cn.zhang.controller;
//定义自己的处理器
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @Controller
public class MyController{ @RequestMapping(value="/frist.do",produces="text/html;charset=utf-8",method=RequestMethod.POST)
public String frist(){
//制造一个异常
int i=5/0;
System.out.println(i);
return "forward:/hello.jsp";
}
}

4.applicationContext.xml(Spring的配置文件)

<?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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 使用注解方式完成映射 -->
<context:component-scan base-package="cn.zhang.controller"></context:component-scan>
<!-- mvc的注解驱动 -->
<mvc:annotation-driven />
<!-- 注册系统异常处理器 -->
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error.jsp"></property>
<property name="exceptionAttribute" value="ex"></property>
</bean> </beans>

测试展示:

点击测试,由于我们在自己的处理器制造了一个异常,所以它会跳到错误页面

二:实现Spring的异常处理接口SimpleMappingExceptionResolver自定义自己的异常处理器

源码介绍:

1.lib包和web.xml一样(不做解释)

2.error包中是指定错误页面

ageerrors.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>年龄错误页面</title>
</head>
<body>年龄错误 ${ex.message }
</body>
</html>

nameerrors.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>名字错误页面</title>
</head>
<body>
名字错误
${ex.message }
</body>
</html>

3.MyController.java

package cn.zhang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
import cn.zhang.exception.UserException; //定义自己的处理器 @Controller
public class MyController{ @RequestMapping(value="/frist.do")
public String frist(Model model,String name,int age) throws UserException{
if (name.equals("admin")) {
throw new NameException("用户名错误");
}
if (age>50) {
throw new AgeException("年龄过大");
}
return "forward:/hello.jsp";
}
}

4.exception包下,指定我们的异常类

UserException.java

package cn.zhang.exception;
//定义UserException继承Exception
public class UserException extends Exception { private static final long serialVersionUID = 1L; public UserException() {
super();
// TODO Auto-generated constructor stub
} public UserException(String message) {
super(message);
// TODO Auto-generated constructor stub
} }

AgeException.java

package cn.zhang.exception;
//继承UserException父类
public class AgeException extends UserException { private static final long serialVersionUID = 1L; public AgeException() {
super();
// TODO Auto-generated constructor stub
} public AgeException(String message) {
super(message);
// TODO Auto-generated constructor stub
} }

NameException.java

package cn.zhang.exception;
//继承UserException父类
public class NameException extends UserException { private static final long serialVersionUID = 1L; public NameException() {
super();
// TODO Auto-generated constructor stub
} public NameException(String message) {
super(message);
// TODO Auto-generated constructor stub
} }

5.applicationContext.xml(Spring的配置文件)

<?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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 使用注解方式完成映射 -->
<context:component-scan base-package="cn.zhang.controller"></context:component-scan>
<!-- mvc的注解驱动 -->
<mvc:annotation-driven />
<!-- 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器 -->
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error.jsp"></property>
<property name="exceptionAttribute" value="ex"></property>
<!-- 指定错误到指定页面 -->
<property name="exceptionMappings">
<props>
<prop key="cn.zhang.exception.AgeException">error/ageerrors.jsp</prop>
<prop key="cn.zhang.exception.NameException">error/nameerrors.jsp</prop>
</props>
</property> </bean> </beans>

结果展示:

 三:实现HandlerExceptionResolver 接口自定义异常处理器 

要修改的代码:

1.MyHandlerExceptionResolver.java--定义自己的异常处理器(实现HandlerExceptionResolver接口)

package cn.zhang.resolvers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
/**
* 定义自己的异常处理器(实现HandlerExceptionResolver接口)
* @author zhangzong
*
*/
public class MyHandlerExceptionResolver implements HandlerExceptionResolver{ public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv=new ModelAndView();
mv.addObject("ex",ex); mv.setViewName("/errors.jsp"); if(ex instanceof NameException){
mv.setViewName("/error/nameerrors.jsp");
} if(ex instanceof AgeException){
mv.setViewName("/error/ageerrors.jsp");
} return mv;
} }

2.applicationContext.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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 使用注解方式完成映射 -->
<context:component-scan base-package="cn.zhang.controller"></context:component-scan>
<!-- mvc的注解驱动 -->
<mvc:annotation-driven />
<!-- 注册自定义异常处理器 -->
<bean class="cn.zhang.resolvers.MyHandlerExceptionResolver"/>
</beans>

其他的相同,不作解释

 四:使用注解@ExceptionHandler实现异常处理

源码介绍:

1.其他配置相同(不做解释)

2.MyController.java--继承我们自己定义的注解异常处理器MyHandlerExceptionResolver

package cn.zhang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
import cn.zhang.exception.UserException;
import cn.zhang.resolvers.MyHandlerExceptionResolver; //定义自己的处理器
//继承我们自己定义的注解异常处理器MyHandlerExceptionResolver
@Controller
public class MyController extends MyHandlerExceptionResolver{ @RequestMapping(value="/frist.do")
public String frist(Model model,String name,int age) throws UserException{
if (name.equals("admin")) {
throw new NameException("用户名错误");
}
if (age>50) {
throw new AgeException("年龄过大");
}
return "forward:/hello.jsp";
}
}

3.MyHandlerExceptionResolver.java--定义自己的异常处理器(使用注解)

package cn.zhang.resolvers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
/**
* 定义自己的异常处理器(使用注解)
* @author zhangzong
*
*/
@Controller
public class MyHandlerExceptionResolver{ @ExceptionHandler
public ModelAndView resolveException(Exception ex) { ModelAndView mv=new ModelAndView();
mv.addObject("ex",ex); mv.setViewName("/errors.jsp"); if(ex instanceof NameException){
mv.setViewName("/error/nameerrors.jsp");
} if(ex instanceof AgeException){
mv.setViewName("/error/ageerrors.jsp");
} return mv;
} }

4.applicationContext.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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 使用注解方式完成映射 -->
<context:component-scan base-package="cn.zhang.controller"></context:component-scan>
<!-- mvc的注解驱动 -->
<mvc:annotation-driven /> <!-- 注册自定义异常处理器 -->
<bean class="cn.zhang.resolvers.MyHandlerExceptionResolver"/>
</beans>

效果和上相同,这里不做展示

SpringMVC中的异常处理集锦的更多相关文章

  1. SpringMVC 中的异常处理

    目录 1.搭建编码分析 2.编写异常类 3.编写自定义异常处理器 4.在springmvc.xml中配置异常处理器 5.编写Error.jsp.index.jsp页面 6.编写collector代码模 ...

  2. SpringMVC中的异常处理

    springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑. 1. 异常处理思路 系统中异常包括两类:预期异常和运行时异常RuntimeExc ...

  3. springmvc中的异常处理方法

    //1.自定义异常处理类       2.编写异常处理器    3.配置异常处理器 package com.hope.exception;/** * 异常处理类 * @author newcityma ...

  4. SpringMVC中的 --- 异常处理

    系统异常处理器SimpleMappingExceptionResolver 处理器方法执行过程中,可能会发生异常,不想看到错误黄页,想看到一个友好的错误提示页. 自定义异常处理器 使用异常处理注解

  5. 【SpringMVC学习07】SpringMVC中的统一异常处理

    我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手段减少运行时异常的发生.在开发中,不管是dao层 ...

  6. (转)SpringMVC学习(八)——SpringMVC中的异常处理器

    http://blog.csdn.net/yerenyuan_pku/article/details/72511891 SpringMVC在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常 ...

  7. JavaEE开发之SpringMVC中的自定义拦截器及异常处理

    上篇博客我们聊了<JavaEE开发之SpringMVC中的路由配置及参数传递详解>,本篇博客我们就聊一下自定义拦截器的实现.以及使用ModelAndView对象将Controller的值加 ...

  8. springmvc中Controller前端控制器的映射与返回数据,以及异常处理

    .@RequestMapping映射 该注解中存的是映射路径的字符串 1.1 value的值是一个数组,也就是说可以定义多个访问路径,同时“.action”可以省略,前端控制器中主要查找主体部分.注意 ...

  9. springmvc 中异常处理

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

随机推荐

  1. 《Entity Framework 6 Recipes》翻译系列(2) -----第一章 开始使用实体框架之使用介绍

    Visual Studio 我们在Windows平台上开发应用程序使用的工具主要是Visual Studio.这个集成开发环境已经演化了很多年,从一个简单的C++编辑器和编译器到一个高度集成.支持软件 ...

  2. .NET 基础 一步步 一幕幕 [前言]

    .NET 基础 一步步 一幕幕 [前言部分] 本人小白一枚,虽然说从去年就开通博客了,到现在也没有写多少东东,虽然工作了,也没有更好得总结.故此重新祭出博客园法宝,修炼技术,争取早日走上大神之位. 故 ...

  3. struts1二:基本环境搭建

    首先建立一个web项目 引入需要的jar包 建立包com.bjpowernode.struts创建LoginAction package com.bjpowernode.struts; import ...

  4. salesforce 零基础学习(四十七) 数据加密简单介绍

    对于一个项目来说,除了稳定性以及健壮性以外,还需要有较好的安全性,此篇博客简单描述salesforce中关于安全性的一点小知识,特别感谢公司中的nate大神和鹏哥让我学到了新得知识. 项目简单背景: ...

  5. slave IO流程之一:mysql登陆过程(mysql_real_connect)

    最近看了slave IO的源码,发现slave IO的写relay log貌似是单线程单连接的,这让我有点小失望. slave IO的主函数是handle_slave_io,处理流程如下: 图1 ha ...

  6. UpdateData(TRUE)与UpdateData(FALSE)的使用

    二者是更新对话框的控件与变量. 1.先要建立对应关系 如 编辑框IDC_Edit  和 变量 m_name DDX_Text(pDX, IDC_EDIT, m_name); 2.若是在编辑框输入名字 ...

  7. Memory Management in Open Cascade

    Open Cascade中的内存管理 Memory Management in Open Cascade eryar@163.com 一.C++中的内存管理 Memory Management in ...

  8. 【转】C# using的三种使用方法

    原文地址http://www.cnblogs.com/fashui/archive/2011/09/29/2195061.html,感谢心茶前辈的总结. 1.using指令 using+命名空间,这种 ...

  9. CSS中div覆盖另一个div

    将一个div覆盖在另一个div上有两种手段:一是设置margin为负值,二是设置绝对定位. 可以根个人情况设置z-index的值 1->position 为absolute的情况 <htm ...

  10. Web APi之控制器选择Action方法过程(九)

    前言 前面我们叙述了关于控制器创建的详细过程,在前面完成了对控制器的激活之后,就是根据控制器信息来查找匹配的Action方法,这就是本节要讲的内容.当请求过来时首先经过宿主处理管道然后进入Web AP ...