處理NETCTOSS項目中的異常
-
問題:
- 使用@ExceptionHandler處理LoginController中的業務異常:
- 修改LoginController,增加異常處理方法,並使用@ExceptionHandler處理業務異常:
@ExceptionHandler public String execute(HttpServletRequest request,HttpServletResponse response, Exception e) throws Exception { if(e instanceof AdminCodeException || e instanceof PasswordException) { //業務異常自己處理 request.setAttribute("message", e.getMessage()); request.setAttribute("adminCode", request.getParameter("adminCode")); request.setAttribute("password", request.getParameter("password")); return "main/login"; } else { //系統異常拋出,交給Spring處理 throw e; } }
- 修改LoginController,增加異常處理方法,並使用@ExceptionHandler處理業務異常:
- 使用SimpleMappingExceptionResolver處理系統異常:
- 配置spring-mvc.xml,增加SimpleMappingExceptionResolver
<!--處理系統異常--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">main/error</prop> </props> </property> </bean>
- 配置spring-mvc.xml,增加SimpleMappingExceptionResolver
- 在WEB-INF/jsp/main下,創建系統錯誤頁面error.jsp,代碼如下:
<%@ page pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>達內-NetCTOSS</title> <!-- 當前: netctoss-trySSM/login/checkLogin.do 目標: netctoss-trySSM/styles/global.css --> <link type="text/css" rel="stylesheet" media="all" href="../styles/global.css" /> <link type="text/css" rel="stylesheet" media="all" href="../styles/global_color.css" /> <script language="javascript" type="text/javascript"> var timer; //啓動跳轉的定時器 function startTimes() { timer = window.setInterval(showSecondes,1000); } var i = 5; function showSecondes() { if (i > 0) { i--; document.getElementById("secondes").innerHTML = i; } else { window.clearInterval(timer); /* 目標: netctoss-trySSM/login/toLogin.do */ location.href = "/netctoss-trySSM/login/toLogin.do"; } } //取消跳轉 function resetTimer() { if (timer != null && timer != undefined) { window.clearInterval(timer); location.href = "/netctoss-trySSM/login/toLogin.do"; } } </script> </head> <body class="error_page" οnlοad="startTimes();"> <h1 id="error"> 遇到錯誤, <span id="secondes">5</span> 秒後將自動跳轉,立即跳轉請點擊 <a href="javascript:resetTimer();">返回</a> </h1> </body> </html>
- 測試:
- 跳轉到首頁: