为了统一处理代码执行过程中出现的异常。给用户一个更友好的异常界面,须要引入springMVC的异常处理功能,为了演示这个功能,本文实现一个比較经常使用的需求。

将所有的异常归为两类,一类是程序猿自己创建的异常类,还有一类是系统或框架定义的异常类。程序猿自己定义的异常类在界面上输出异常信息,而系统定义好的异常所有统一输出“未知错误”。

引发异常后。跳转到异常页面,而且进行读秒,三秒后自己主动跳转到请求发生的页面,或者由程序猿定义好的页面。

为了实现该功能,首先写一个自己的异常类,我这里命名为MyException,而且加入两个成员变量message和destination,分别表示异常信息和异常页面自己主动跳转的目标页面。

在当中加入getter、setter和构造方法,程序清单例如以下:

package com.elin4it.ssm.controller.exception;

/**
* Description: MyException
* Author: Elin Zhou
* Create: 2015-07-04 13:49
*/
public class MyException extends Exception {
private String message;
//异常产生后跳转的位置。默认跳转到之前的页面
private String destination;

public MyException(){}

public MyException(String message){
super(message);
this.message = message;
}

public MyException(String message,String destination) {
super(message);
this.destination = destination;
this.message = message;
}

public String getDestination() {
return destination;
}

public void setDestination(String destination) {
this.destination = destination;
}

@Override
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}


处理异常的功能。SpringMVC为程序猿提供了HandlerExceptionResolver接口。仅仅要实现当中的resolveException方法。即能够在异常发生时调用该方法处理异常。

所以创建一个类。使事实上现resolveException接口。并加入

public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)


方法。

对于详细异常的处理在此不再赘述,本文主要是为了介绍异常处理的流程。详细业务逻辑依据实际情况而定,这里仅仅贴上为了完毕上文需求而实现的代码。

package com.elin4it.ssm.controller.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Description: MyExceptionResolver
* Author: Elin Zhou
* Create: 2015-07-04 13:49
*/
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
MyException myException = null;
if (e instanceof MyException){
//假设接受到的异常为用户自己定义的异常
myException = (MyException)e;
}else{
//假设接受到的异常为其它系统定义的异常
myException = new MyException("未知错误");
}

if (myException.getDestination()==null){
//假设没有指定异常发生后的目标页面,则自己主动跳转到发起请求的页面

//获取发起请求的完整路径,如http://localhost:8080/ssm/book/bookIndex
String requestURL = httpServletRequest.getHeader("Referer");
//依据'/'把路径切割
String[] splitFromURL = requestURL.split("/");
//得到切割后的子串数量
int count = splitFromURL.length;
//得到最后两端子串。并拼接成逻辑地址
String destination = splitFromURL[count-2]+"/"+splitFromURL[count-1];
myException.setDestination(destination);
}

ModelAndView modelAndView = new ModelAndView();
//把异常传递到request中,用于界面输出的跳转
modelAndView.addObject("exception",myException);

modelAndView.setViewName("error");

return modelAndView;
}
}


上述代码实现的是依据參数推断异常是哪一类,假设是系统定义的则创建一个MyException,而且把message赋值为“未知错误”。然后推断当中的destination是否为null,假设是则将其赋值为用户发生请求的页面。

然后将其赋值到ModelAndView中,然后返回。

最后,须要把异常处理器配置到springmvc中。在springmvc的配置文件里加入处理器类的注入。

<bean class="com.elin4it.ssm.controller.exception.MyExceptionResolver"/>


不许要写id。也不须要配置其它信息。springmvc在装载bean到IOC容器时假设扫描到实现了HandlerExceptionResolver接口的类,则将其作为异常处理器。

最后贴上測试的controller方法和异常处理的jsp页面

@RequestMapping("/addBook")
public String addBook()throws Exception{
//測试自己定义异常
if (1==1)
throw new MyException("測试异常");
//測试系统定义的异常
int a = 10/0;
return "book/addBook";
}
<%--
Created by IntelliJ IDEA.
User: elin
Date: 15-7-4
Time: 下午1:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误发生</title>
<script type="text/javascript">
function countDown(secs,surl){
var jumpTo = document.getElementById('jumpTo');
jumpTo.innerHTML=secs;
if(--secs>0){
setTimeout("countDown("+secs+",'"+surl+"')",1000);
}
else{
location.href=surl;
-ma
}
}
</script>
</head>
<body>
<h1>${exception.message}</h1>

<a href="<%=request.getContextPath()%>/${exception.destination}"><span id="jumpTo">3</span>秒后系统会自己主动跳转,也可点击本处直接跳</a>
<script type="text/javascript">
countDown(3,'<%=request.getContextPath()%>/${exception.destination}');
</script>
</body>
</html>