按上回繼續,前面寫過一篇Spring MVC下的異常處理、及Spring MVC下的ajax異常處理,今天看下換成velocity模板引擎后,如何處理異常頁面:
一、404錯誤、500錯誤
1 <error-page> 2 <error-code>404</error-code> 3 <location>/nopage.do</location> 4 </error-page> 5 6 <error-page> 7 <error-code>500</error-code> 8 <location>/error.do</location> 9 </error-page>
web.xml中添加這二項,注意locatoion節點,不再是指定成物理文件路徑,而是Spring MVC中Controller里具體方法映射的URI
1 @RequestMapping(value = "/nopage.do", method = RequestMethod.GET) 2 public String pageNotFound(Locale locale, Model model) throws Exception { 3 return "errors/404"; 4 } 5 6 @RequestMapping(value = "/error.do", method = RequestMethod.GET) 7 public String innerError(Locale locale, Model model) throws Exception { 8 return "errors/500"; 9 }
上面是Controller的處理
二、常規異常的處理
Controller里的處理還是跟以前一樣,關鍵是errors/error.vm這個模板文件如何寫:
1 <!doctype html> 2 <html> 3 <head> 4 #parse("comm/header.vm") 5 #set($ex=$request.getAttribute("ex")) 6 <title>ERROR</title> 7 </head> 8 <body style="margin:20px"> 9 <H2> 10 錯誤:$ex.class.simpleName 11 </H2> 12 <hr/> 13 <P> 14 <strong>錯誤描述:</strong>$ex.message 15 </P> 16 17 <P> 18 <strong>詳細信息:</strong> 19 </P> 20 <pre> 21 #foreach($stack in $ex.getStackTrace()) 22 $stack.toString() 23 #end 24 </pre> 25 </body> 26 </html>
注意:5、10、21-23這幾行
三、ajax異常的處理
這里要在BaseController里直接返回json字符串,參考下面的代碼:
1 @ExceptionHandler 2 public String exp(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception { 3 String resultViewName = "errors/error"; 4 5 // 記錄日志 6 logger.error(ex.getMessage(), ex); 7 8 // 根據不同錯誤轉向不同頁面 9 if (ex instanceof BusinessException) { 10 resultViewName = "errors/biz-error"; 11 } else { 12 // 異常轉換 13 //ex = new Exception("服務器忙,請稍候重試!"); 14 } 15 16 String xRequestedWith = request.getHeader("X-Requested-With"); 17 if (!StringUtils.isEmpty(xRequestedWith)) { 18 // ajax請求 19 ResponseUtil.OutputJson(response, "{\"error\":\"" + ex.getClass().getSimpleName() + "\",\"detail\":\"" + ex.getMessage() + "\"}"); 20 } 21 request.setAttribute("ex", ex); 22 return resultViewName; 23 }
關鍵點有2個,方法簽名里增加HttpServletResponse response,然后19行,直接輸出Json字符串,其中用到了一個ResponseUtil類,該類的主要代碼如下:
1 public static void OutputContent(HttpServletResponse response, 2 String contentType, String content) throws IOException { 3 response.setContentType(contentType + ";charset=utf-8"); 4 response.setCharacterEncoding("UTF-8"); 5 PrintWriter out = response.getWriter(); 6 out.println(content); 7 out.flush(); 8 out.close(); 9 } 10 11 public static void OutputJson(HttpServletResponse response, String content) 12 throws IOException { 13 OutputContent(response, "application/json", content); 14 }