public class CustomException extends Exception { public CustomException(String message) { super(message); this.message = message; } // 異常信息 private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }}全局異常處理器思路:系統遇到異常,在程序中手動拋出,dao拋給service,service拋給Controller,Controller拋給前端控制器,前端控制器調用全局異常處理器全局異常處理器處理思路:解析出異常類型如果該異常類型是系統自定義的異常,直接取出異常信息,在錯誤頁面顯示如果該異常類型不是系統自定義的異常,構造一個自定義的異常類型(信息為“未知錯誤“)springmvc提供了一個HandlerExceptionResolver接口public class CustomExceptionResolver implements HandlerExceptionResolver { public CustomExceptionResolver() { // TODO 自動生成的構造函數存根 } @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) { // TODO 自動生成的方法存根 exception.printStackTrace(); CustomException customException = null; //如果拋出的是系統自定義異常則直接轉換 if(exception instanceof CustomException){ customException = (CustomException)exception; }else{ //如果拋出的不是系統自定義異常則重新構造一個未知錯誤異常。 customException = new CustomException("未知錯誤,請與系統管理 員聯系!"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", customException.getMessage()); modelAndView.setViewName("error"); return modelAndView; }}jsp錯誤頁面<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%><!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>錯誤頁面</title></head><body>您的操作出現錯誤如下:<br/>${message }</body></html>異常處理器配置在springmvc.xml中添加:<!-- 異常處理器 --> <bean id="handlerExceptionResolver" class="cn.itcast.ssm.controller.exceptionResolver.CustomExceptionResolver"/>
新聞熱點
疑難解答