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"/>
新闻热点
疑难解答