可單例開發、典型的教科書式的mvc構架----springmvc----day02(三)
6.5在springmvc.xml配置全域性異常處理器
<!-- 全域性異常處理器 只要實現HandlerExceptionResolver介面就是全域性異常處理器 -->
<bean class="com.changemax.ssm.exception.CustomExceptionResolver"></bean>
6.6異常測試
在controller、service、dao中任意一處需要手動丟擲異常。
如果是程式中手動丟擲的異常,在錯誤頁面中顯示自定義的異常資訊,如果不是手動丟擲異常說明是一個執行時異常,在錯誤頁面只顯示“未知錯誤”。
在商品修改的controller方法中丟擲異常:
// 商品修改頁面顯示
// @RequestMapping("/editItems")
// 限制http的請求方法
@RequestMapping(value = "/editItems", method = { RequestMethod.GET, RequestMethod.POST })
// @@RequestParam裡面指定request傳入引數名稱和形參進行形參繫結
// 通過required屬性指定引數是否傳入
// 通過defaultValue可以設定預設值,如果id引數沒有傳入,將預設值和形參繫結
public String editItems(Model model,
@RequestParam(value = "id", required = true/* , defaultValue="" */) Integer items_id) throws Exception {
// 呼叫sevice根據商品id查詢商品資訊
ItemsCustom itemsCustom = itemsService.selectItemById(items_id);
// ModelAndView modelAndView = new ModelAndView();
//
// // 相當於resquest的setAttribute,在jsp頁面中通過itemsList取資料
// modelAndView.addObject("itemsCustom", itemsCustom);
//
// // 指定檢視
// // 通過springmvc配置檔案,可以省掉jsp路徑的字首和字尾
// modelAndView.setViewName("items/editItems");
System.out.println(itemsCustom.toString());
model.addAttribute("itemsCustom", itemsCustom);
return "items/editItems";
}
在service介面中丟擲異常:
@Override
public ItemsCustom selectItemById(Integer id) throws Exception {
Items items = itemsMapper.selectByPrimaryKey(id);
// 通過ItemsMappCustom查詢
ItemsCustom itemsCustom = new ItemsCustom();
BeanUtils.copyProperties(items, itemsCustom);
return itemsCustom;
}
如果與業務功能相關的異常,建議在service中丟擲異常。
與業務功能沒有關係的異常,建議在controller中丟擲。
上邊的功能,建議在service中丟擲異常。