1.概述
介紹如何實現異常捕獲過濾器。
2.技術要點
本實例主要是在過濾器Filter的doFilter()方法中,對執行過濾器鏈的chain的doFilter()語句處添加try…catch異常捕獲語句,然后在chach語句中,循環異常對象,直到找出根異常為止。
3.具體實現
(1)創建Filter實現類ExceptionFilter.java,利用throwable拋出異常,去捕捉異常原因並轉到相應的頁面中主要代碼為:
public class ExceptionFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); } catch (Exception e) { //如果有異常則捕捉 Throwable rootCause = e; while (rootCause.getCause() != null) { rootCause = rootCause.getCause(); } String errormessage = rootCause.getMessage(); //異常根本 errormessage = errormessage == null ? "異常:" + rootCause.getClass().getName() : errormessage; //中止傳遞異常的原因 request.setAttribute("errormessage", errormessage); request.setAttribute("e", e); if (rootCause instanceof LoginException) { //1轉到登錄頁面 request.getRequestDispatcher("/LoginException.jsp").forward( request, response); } else if (rootCause instanceof OperationException) { //2轉到操作頁面 request.getRequestDispatcher("/OperationException.jsp").forward( request, response); } else { request.getRequestDispatcher("/exception.jsp").forward(request, //其它異常 response); } } } public void init(FilterConfig arg0) throws ServletException { } }
(2)創建LoginException.jsp登錄異常頁面主要代碼為:
<div align="center" style="font-size: large;">后台操作</div> <form action=""> <table align="center"> <tr> <td>帳號</td> <td><input type="text" name="account" /></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="password" /></td> </tr> <tr> <td align="center" colspan="2"><input type="submit" value=" 登錄 " /> <input type="submit" value="退出"/></td> </tr> </table> </form> <div class="error" align="center"> ${ errormessage } </div>
(3)創建OperationException操作異常頁面主要代碼如下:
<div class="error" align="center"> ${ errormessage } <a href="javascript:history.go(-1); ">返回上一級操作</a> </div>
(4)創建Exceptionmain.jsp頁面,關鍵代碼如下:
<% String action = request.getParameter("action"); if("OperationException".equals(action)){ throw new OperationException("此操作失敗. "); } else if("LoginException".equals(action)){ throw new LoginException("請您登陸后再進行此項操作. "); } else if("exception".equals(action)){ Integer.parseInt("mull空傳遞參數"); } %> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>異常捕捉過濾器</title> </head> <body> <table align="left" cellpadding="2" cellspacing="2"> <Tr><td><a href="${ pageContext.request.requestURI }?action=OperationException">過濾操作</a></td></Tr> <tr><td><a href="${ pageContext.request.requestURI }?action=LoginException">過濾登錄</a></td></tr> <Tr><td><a href="${ pageContext.request.requestURI }?action=exception">過濾異常</a></td></Tr> </table>