zoukankan      html  css  js  c++  java
  • SpringMVC异常处理机制

    系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试等手段减少运行时异常的发生。

    异常处理两种方式

    ① 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

    ② 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器

    springMvc自带的异常处理

    我们直接在springMvc.xml配置文件中配置即可

    <!--    配置springMvc自带的异常处理器-->
    
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="defaultErrorView" value="error"/><!--默认的一场,默认的返回的返回视图是error界面-->
            <property name="exceptionMappings" >  <!--异常的处理分发-->
                <map>
                    <entry key="java.lang.ClassCastException" value="error1"/><!--当异常是数据转换异常,返回的是error界面-->
                </map>
            </property>
        </bean>

    注意:(我们上面返回的界面信息,是因为我们在springMvc.xml中配置了视图解析器)

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"/>
            <property name="suffix" value=".jsp"/>
        </bean>

    eg;

    <!--    配置springMvc自带的异常处理器-->
    
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="defaultErrorView" value="error"/><!--默认的返回的返回视图-->
            <property name="exceptionMappings" >  <!--异常的处理分发-->
                <map>
                    <entry key="java.lang.ClassCastException" value="error1"/><!--当异常是数据转换异常-->
                    <entry key="com.springMvc.exception.MyException" value="error2"/><!--如果跑出来的是我们自定义的异常,那么跳转到error2界面-->
                </map>
            </property>
        </bean>

     

    自定义异常

    实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器

    系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理,如下图:

    自定义异常处理步骤

    ①创建异常处理器类实现HandlerExceptionResolver

    2:配置异常处理器

    3:编写异常页面

    4:测试异常跳转

    1: 首先创建一个类去实现HandlerExceptionResolver接口

    public class MyExceptionResolver implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
            /*
            处理异常出现后的代码
            */
            //创建ModelAndView对象
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("exceptionPage"); //出现异常后跳转的界面
            return modelAndView;
        }
    }

    2:去springMvc.xml中配置自定义的异常处理器

    <!-- 配置自定义异常处理器-->
        <bean class="com.springMvc.resolver.MyExceptionResolver"/><!--指定你的自定义异常处理器位置-->

    3:编写异常页面

    前端界面就是你的自定义异常中modelandView设置的界面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    
    
    这是最终的异常界面!!!! 手动实现的异常
    </body>
    </html>

    上面的异常是我们只要在任意的代码中出错了都会跳转到自定义异常设置的界面

    下面演示下我们在实际使用中的异常处理

    eg:

    Service层:

    MyDemoService接口

    public interface MyDemoService {
    
        void show1();
        void show2();
        void show3() throws FileNotFoundException;
        void show4();
        void show5() throws MySelfException;
    }
    接口 MyDemoService

    实现类MyDemoServiceImpl

    @Service // 将这个service类注入到spring容器中
    public class MyDemoServiceImpl implements MyDemoService {
        @Override
        public void show1() {
            System.out.println("抛出类型转换异常");
            Object str = "我是张三";
            Integer num = (Integer)str;
        }
    
        @Override
        public void show2() {
            System.out.println("抛出除零异常");
            int num = 1/0;
        }
    
        @Override
        public void show3() throws FileNotFoundException {
            System.out.println("文件找不到异常");
            FileInputStream fis = new FileInputStream("C:/xxx/xxx/xxx.txt");
        }
    
        @Override
        public void show4() {
            System.out.println("空指针异常");
            String str = null;
            str.length();
        }
    
        @Override
        public void show5() throws MySelfException {
            System.out.println("自定义异常....");
            throw new MySelfException();
        }
    }
    MyDemoServiceImpl

    web层

    类MySelfExceptionDemo

    @Controller//将这个web类加入到spring容器中
    public class MySelfExceptionDemo {
    
        @Autowired//将此接口的及其实现类注入进来
        private MyDemoService myDemoService;
    
        @ResponseBody
        @RequestMapping("myself")
        public void myself() throws MySelfException {
            myDemoService.show1();
    //        myDemoService.show5();
        }
    
    }

    自定义异常处理类:MySelfExceptionResolver

    public class MySelfExceptionResolver implements HandlerExceptionResolver {
    
        /**
         *
         * @param httpServletRequest
         * @param httpServletResponse
         * @param o
         * @param e  参数异常对象
         * @return modelAndView 跳转信息
         */
        @Override
        public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    
            /*
            参数Exception: 异常对象
            返回值ModelAndView:跳转到错误视图信息
             */
            ModelAndView modelAndView = new ModelAndView();
            if(e instanceof MySelfException){
                modelAndView.addObject("info","自定义异常处理");
            }else if(e instanceof ClassCastException){
                modelAndView.addObject("info","类转化异常");
            }
            modelAndView.setViewName("myselfException");//跳转到myselfException前端界面
            return modelAndView;
    
    
        }
    }

    前端:myselfException.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8" isELIgnored="false"%>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    
    
    This is  ${info} 异常处理
    
    </body>
    </html>

    将自定义的异常处理配置到springMvc的配置文件springMvc.xml中

    <!--    配置自定义异常处理器-->
        <bean class="com.springMvc.resolver.MySelfExceptionResolver"/>
  • 相关阅读:
    程序员常用资源工具集合(建议收藏)
    程序员常用资源工具集合(建议收藏)
    16个烧光你脑细胞的悖论
    2.2_模型的选择
    2.1_Scikit-learn数据集
    Sklearn数据集与机器学习
    1.4_数据的特征选择
    1.4_特征的选择
    1.3_数据的特征预处理
    1.2_数据的特征抽取
  • 原文地址:https://www.cnblogs.com/zhaoyunlong/p/14310228.html
Copyright © 2011-2022 走看看