zoukankan      html  css  js  c++  java
  • SpringMvc 全局异常处理

    MyExceptionHandler

    package exception;
    
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    
    @ControllerAdvice
    public class MyExceptionHandler {//不是控制器,仅仅是 用于处理异常的类
    
        @ExceptionHandler(Exception.class)
        public ModelAndView handlerArithmeticException2(Exception e) {
            ModelAndView mv = new ModelAndView("error");
            System.out.println(e + "============" + "该@ControllerAdvice中的异常处理方法,可以处理任何类中的异常");
            mv.addObject("er", e);
            return mv;
        }
    }

    SecondSpringMVCHandler

    package handler;
    
    import exception.MyArrayIndexOutofBoundsException;
    import org.springframework.http.HttpStatus;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseStatus;
    
    @Controller
    @RequestMapping("second")
    public class SecondSpringMVCHandler {
    
        @RequestMapping("testExceptionHandler")
        public String testExceptionHandler() {
            System.out.println(1 / 0);
            return "success";
        }
    
        @RequestMapping("testExceptionHandler2")
        public String testExceptionHandler2() {
            int[] nums = new int[2];
            System.out.println(nums[2]);//ArrayIndexOutOfBoundsException
            return "success";
        }
    }

    component-scan

    <context:component-scan base-package="exception"></context:component-scan>

    error.jsp

    <%@ 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>Insert title here</title>
    </head>
    <body>
            ${requestScope.er }
    </body>
    </html>

  • 相关阅读:
    ubuntu 更新软件
    如何在linux(lubuntu)下搭建C/C++开发环境
    Linux下如何查看版本信息
    知识点笔记
    Require.js中使用jQuery 插件
    async中常用总结
    node.js在遇到“循环+异步”时的注意事项
    前端性能优化
    生产/消费者问题
    线程与内存
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/11882159.html
Copyright © 2011-2022 走看看