码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC异常处理

时间:2015-07-05 09:43:32      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

为了统一处理代码运行过程中出现的异常,给用户一个更友好的异常界面,需要引入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>

版权声明:本文为博主原创文章,未经博主允许不得转载。

SpringMVC异常处理

标签:

原文地址:http://blog.csdn.net/u011403655/article/details/46756887

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!