可单例开发、典型的教科书式的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中抛出异常。

浙公网安备 33010602011771号