SpringMVC異常處理

爲了統一處理代碼運行過程當中出現的異常,給用戶一個更友好的異常界面,須要引入springMVC的異常處理功能,爲了演示這個功能,本文實現一個比較經常使用的需求。javascript

將全部的異常歸爲兩類,一類是程序員本身建立的異常類,另外一類是系統或框架定義的異常類。程序員本身定義的異常類在界面上輸出異常信息,而系統定義好的異常所有統一輸出「未知錯誤」。
引起異常後,跳轉到異常頁面,而且進行讀秒,三秒後自動跳轉到請求發生的頁面,或者由程序員定義好的頁面。html

爲了實現該功能,首先寫一個本身的異常類,我這裏命名爲MyException,而且添加兩個成員變量message和destination,分別表示異常信息和異常頁面自動跳轉的目標頁面。
在其中添加getter、setter和構造方法,程序清單以下:java

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)

方法。web

對於具體異常的處理在此再也不贅述,本文主要是爲了介紹異常處理的流程,具體業務邏輯根據實際狀況而定,這裏只貼上爲了完成上文需求而實現的代碼。spring

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中,而後返回。markdown

最後,須要把異常處理器配置到springmvc中,在springmvc的配置文件中添加處理器類的注入。mvc

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

不準要寫id,也不須要配置其餘信息,springmvc在裝載bean到IOC容器時若是掃描到實現了HandlerExceptionResolver接口的類,則將其做爲異常處理器。app

最後貼上測試的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>
相關文章
相關標籤/搜索