亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Springmvc自定義異常處理器實(shí)現(xiàn)流程解析

 更新時間:2020年07月07日 11:32:34   作者:林汐-  
這篇文章主要介紹了Springmvc自定義異常處理器實(shí)現(xiàn)流程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

當(dāng)dispatchServlet接收到controller拋出的異常時,會將異常交由 HandlerExceptionResolver

異常處理器處理!我們可以創(chuàng)建自定義異常處理器實(shí)現(xiàn)該接口來處理自定義異常

1) 自定義異常類

public class MyException extends Exception {
  // 異常信息
  private String message;
 
  public MyException() {
    super();
  }
 
  public MyException(String message) {
    super();
    this.message = message;
  }
 
  public String getMessage() {
    return message;
  }
 
  public void setMessage(String message) {
    this.message = message;
  }
 
}

2)自定義異常處理器

public class CustomHandleException implements HandlerExceptionResolver {
 
  @Override
  public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
      Exception exception) {
    // 定義異常信息
    String msg;
 
    // 判斷異常類型
    if (exception instanceof MyException) {
      // 如果是自定義異常,讀取異常信息
      msg = exception.getMessage();
    } else {
      // 如果是運(yùn)行時異常,則取錯誤堆棧,從堆棧中獲取異常信息
      Writer out = new StringWriter();
      PrintWriter s = new PrintWriter(out);
      exception.printStackTrace(s);
      msg = out.toString();
 
    }
 
    // 把錯誤信息發(fā)給相關(guān)人員,郵件,短信等方式
    // TODO
 
    // 返回錯誤頁面,給用戶友好頁面顯示錯誤信息
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("msg", msg);
    modelAndView.setViewName("error");
 
    return modelAndView;
  }
}

3)在springmvc.xml中配置異常處理器

<!-- 配置全局異常處理器 -->
<bean
id="customHandleException" class="cn.itcast.ssm.exception.CustomHandleException"/>

4)定制錯誤頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
  <h1>系統(tǒng)發(fā)生異常了!</h1>
  <br />
  <h1>異常信息</h1>
  <br />
  <h2>${msg }</h2>
 
</body>
</html>

5)測試異常處理

@RequestMapping(value = "/item/itemlist.action")
public ModelAndView itemList() throws MyException{
    
    List<Items> list = itemService.selectItemsList();
    
    if(true){
      throw new MyException("商品列表不能為空!!");
    }
    
    ModelAndView mav = new ModelAndView();
    mav.addObject("itemList", list);
    mav.setViewName("itemList");
    return mav;
  }

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論