springmvc异常处理

来源:互联网 发布:java旋转爱心代码 编辑:程序博客网 时间:2024/06/05 23:42

1.springmvc异常处理-全局异常处理器开发

public class CustomException extends Exception {//异常信息public String message;public CustomException(String message){super(message);this.message = message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}

package cn.itcast.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 {/** * (非 Javadoc) * <p>Title: resolveException</p> * <p>Description: </p> * @param request * @param response * @param handler * @param ex 系统 抛出的异常 * @return * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) */@Overridepublic ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {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;}}

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>错误提示</title></head><body>${message }</body></html>

<!-- 全局异常处理器只要实现HandlerExceptionResolver接口就是全局异常处理器 --><bean class="cn.itcast.ssm.exception.CustomExceptionResolver"></bean>


2.springmvc异常处理-抛出异常

// 编辑(根据ID查询)@RequestMapping(value = "/editItems", method = { RequestMethod.POST,RequestMethod.GET })// @RequestParam里边指定request传入参数名称和形参进行绑定。// 通过required属性指定参数是否必须要传入// 通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。public String editItems(Model model,@RequestParam(value = "id", required = true) Integer items_id)throws Exception {// 调用service根据商品id查询商品信息ItemsCustom itemsCustom = itemsService.findItemsById(items_id);//判断商品是否为空,根据id没有查询到商品,抛出异常,提示用户商品信息不存 在//if(itemsCustom == null){//throw new CustomException("修改的商品信息不存在!");//}model.addAttribute("items", itemsCustom);return "items/editItems";}

@Overridepublic ItemsCustom findItemsById(Integer id) throws Exception {Items items = itemsMapper.selectByPrimaryKey(id);if(items==null){throw new CustomException("修改的商品信息不存在!");}ItemsCustom itemsCustom = null;//将items的属性值拷贝到itemsCustomif(items!=null){itemsCustom = new ItemsCustom();BeanUtils.copyProperties(items, itemsCustom);}return itemsCustom;}


3.

4.

5.

6.

0 0
原创粉丝点击