<!-- 統一異常處理 -->html
<bean class="com.zhxjz.common.CommonExceptionResolver" />java
CommonExceptionResolver.javaweb
package com.zhxjz.common; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; /** * 異常解析器 * * @author caozj */ public class CommonExceptionResolver implements HandlerExceptionResolver { private static Log logger = LogFactory .getLog(CommonExceptionResolver.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { logger.error("發生異常", ex); ModelAndView model = new ModelAndView(); if (ex instanceof RuntimeException) { model.setViewName("error/forbid"); } else { model.setViewName("error/error"); model.addObject("message", ex.getMessage()); } return model; } }
error.jspspring
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Exception</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> Error:${message} <br /> <a href="#" onclick="history.back();">返回</a> <br> </body> </html>
forbid.jsp
apache
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Exception</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> 您沒有權限訪問 <br /> <a href="#" onclick="history.back();">返回</a> <br> </body> </html>
當執行語句jsp
throw new RuntimeException("攔截成功");ide
時就會被統一異常處理器攔截ui