1. 程式人生 > >【SpringMVC整合MyBatis】springmvc異常處理-全域性異常處理器開發

【SpringMVC整合MyBatis】springmvc異常處理-全域性異常處理器開發

異常處理 1.異常處理思路 系統中異常包括兩類:預期異常和執行時異常RuntimeException,前者通過捕獲異常從而獲取異常資訊,後者主要通過規範程式碼開發、測試通過手段減少執行時異常的發生。 系統的dao、service、controller出現都通過throws Exception向上丟擲,最後由springmvc前端控制器交由異常處理器進行異常處理。

springmvc提供全域性異常處理器(一個系統只有一個異常處理器)進行統一異常處理。

2.自定義異常類

對不同的異常型別定義異常類,繼承Exception。 -

package cn.edu.hpu.ssm.exception;   //系統自定義異常處理類,針對預期的異常,需要在程式中丟擲此類的異常 public class CustomException extends Exception{          //異常資訊     private String message;          public CustomException(String message){         super(message);         this.message=message;     }         public String getMessage() {         return message;     }         public void setMessage(String message) {         this.message = message;     } } 3.全域性異常處理器

思路: 系統遇到異常,在程式中手動丟擲,dao拋給service、service給controller、controller拋給前端控制器,前端控制器呼叫全域性異常處理器。

全域性異常處理器處理思路:     解析出異常型別。     如果該 異常型別是系統 自定義的異常,直接取出異常資訊,在錯誤頁面展示。     如果該 異常型別不是系統 自定義的異常,構造一個自定義的異常型別(資訊為“未知錯誤”)。

springmvc提供一個HandlerExceptionResolver介面 

package cn.edu.hpu.ssm.exception;   import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView;   //全域性異常處理器 public class CustomExceptionResolver implements HandlerExceptionResolver{       //系統丟擲的異常     @Override     public ModelAndView resolveException(HttpServletRequest request,             HttpServletResponse response, Object handler, Exception ex) {         //handler就是處理器介面卡要執行的Handler物件(只有method)         //解析出異常型別。                  //如果該 異常型別是系統 自定義的異常,直接取出異常資訊,在錯誤頁面展示。         CustomException customException=null;         if(ex instanceof CustomException){             customException=(CustomException)ex;                      }else{             //如果該 異常型別不是系統 自定義的異常,構造一個自定義的異常型別(資訊為“未知錯誤”)。             customException=new CustomException("未知錯誤");         }           //錯誤資訊         String message=customException.getMessage();                  ModelAndView modelAndView=new ModelAndView();                  //將錯誤資訊傳到頁面         modelAndView.addObject("message",message);                  //指向到錯誤介面         modelAndView.setViewName("error");                  return modelAndView;     }       } 4.錯誤頁面 

在WEB-INF/jsp資料夾下建立error.jsp頁面,內容為:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>   <head>     <base href="<%=basePath%>">          <title>錯誤提示</title>       </head>      <body>     <h1><font color="red">${message }</font></h1><br>   </body> </html>

5.在springmvc.xml配置全域性異常處理器 

<!-- 全域性異常處理器      只要你實現了HandlerExceptionResolver介面,這個     類就是一個全域性異常處理器-->     <bean class="cn.edu.hpu.ssm.exception.CustomExceptionResolver"></bean> 6.異常測試 在controller、service、dao中任意一處需要手動丟擲異常。 如果是程式中手動丟擲的異常,在錯誤頁面中顯示自定義的異常資訊,如果不是手動丟擲異常說明是一個執行時異常,在錯誤頁面只顯示“未知錯誤”。 在商品修改的controller方法中丟擲異常。 

@RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET}) //@RequestParam裡面指定reuqest傳入引數和形參進行繫結。 //通過required屬性指定引數是否必須要傳入 //通過defaultValue可以設定預設值,如果id引數沒有傳入,將預設值和形參繫結     public String editItems(Model model,@RequestParam(value="id",required=true,defaultValue="") Integer items_id)throws Exception{                  //呼叫service根據商品id查詢商品資訊         ItemsCustom itemsCustom=itemsService.findItemsById(items_id);         //判斷商品是否為空,根據id沒有查到商品,提示使用者商品資訊並不存在         if(itemsCustom==null){             throw new CustomException("商品的修改資訊不存在!");         }                  //通過形參中的model將model資料傳到頁面         //相當於modelAndView.addObject方法         model.addAttribute("items22",itemsCustom);                  return "items/editItems";     } 其中上面用到的service方法: 

@Override public ItemsCustom findItemsById(Integer id) throws Exception {          Items items=itemsMapper.selectByPrimaryKey(id);     //中間對商品資訊進行業務處理     //...     //最終返回ItemsCustom     ItemsCustom itemsCustom=null;     //將item的內容拷貝到itemsCustom     if(items!=null){         itemsCustom=new ItemsCustom();         BeanUtils.copyProperties(items, itemsCustom);     }          return itemsCustom; } 我們讓id指定一個沒有的數(如4444),則會丟擲我們自定義的異常資訊: 

同樣在service中也可以丟擲異常

如果與業務功能相關的異常,建議在service層丟擲。

如果與業務功能沒有相關的異常,建議在controller層丟擲。