zoukankan      html  css  js  c++  java
  • Spring MVC——异常捕获

    1. 自定义异常类
    public class CustomerException extends Exception {

    private String message;

    public CustomerException() {
    super();
    }

    public CustomerException(String message) {
    super(message);

    this.message = message;
    }

    public String getMessage() {
    return message;
    }

    public void setMessage(String message) {
    this.message = message;
    }
    }

    2. 定义异常处理器,并实现org.springframework.web.servlet.HandlerExceptionResolver接口
    public class CustomerExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {

    CustomerException cex = null;
    if(ex instanceof CustomerException)
    {
    cex = (CustomerException)ex;
    }
    else
    {
    cex = new CustomerException("未知错误!!");
    }

    System.out.println("异常:" + cex.getMessage());

    ModelAndView modelAndView = new ModelAndView();

    //保存错误信息
    modelAndView.addObject("errorMsg", cex.getMessage());

    //指定跳转视图
    modelAndView.setViewName("error");

    return modelAndView;
    }

    }

    3. 在spring-mvc.xml中配置全局异常处理器
    <!-- 自定义全局异常处理器,因为实现了org.springframework.web.servlet.HandlerExceptionResolver接口 -->
    <bean class="com.neuedu.exception.CustomerExceptionHandler"></bean>

    4. 在error.jsp页面显示异常处理器保存的异常信息

    对不起,您的操作引发了异常:${errorMsg}

    5. 异常类应用

    定义dao、service、controller,并在任意层制造异常

    6. 测试

    http://localhost:8088/springMvc_06_exception/index.jsp

  • 相关阅读:
    判断一棵二叉树是否为二叉搜索树
    分离链接法的删除操作函数
    线性探测法的查找函数
    Bzoj1251 序列终结者
    POJ2396 Budget
    Bzoj3531: [Sdoi2014]旅行
    Codeforces Round #389 Div.2 E. Santa Claus and Tangerines
    Codeforces Round #389 Div.2 D. Santa Claus and a Palindrome
    Codeforces Round #389 Div.2 C. Santa Claus and Robot
    Codeforces Round #389 Div.2 B. Santa Claus and Keyboard Check
  • 原文地址:https://www.cnblogs.com/ccw95/p/6168700.html
Copyright © 2011-2022 走看看