• 024 SpringMvc的异常处理


    一:说明

    1.介绍

      Springmvc提供HandlerExceptionResolver处理异常,包括Handler映射,数据绑定,以及目标方法执行。

    2.几个接口的实现类

      AnnotationMethodHandlerExceptionResolver

      DefaultHandlerExceptionResolver

      ResponseStatusExceptionResolver

      SimpleMappingExceptonResolver

      ExceptionHandlerExceptionResolver

      当开发的时候,如果配置了<mvc:annotation-driven>时,就默认配置了一下的实现类:

      ExceptionHandlerExceptionResolver,ResponseStatusExceptionResolver,DefaultHandlerExceptionResolver

    二:ExceptionHandlerExceptionResolver

    1.介绍

      

    2.程序

      可以做到,出现异常,使用springmvc的注解进行处理异常。

     1 package com.spring.it.exception;
     2 
     3 import org.springframework.stereotype.Controller;
     4 import org.springframework.web.bind.annotation.ExceptionHandler;
     5 import org.springframework.web.bind.annotation.RequestMapping;
     6 import org.springframework.web.bind.annotation.RequestParam;
     7 
     8 @Controller
     9 public class ExceptionHandlerDemo {
    10     /**
    11      *异常处理类
    12      */
    13     @RequestMapping("/testExceptionHandlerExceptionResolver")
    14     public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
    15         System.out.println("result="+(10/i));
    16         return "success";
    17     }
    18     
    19     /**
    20      * 异常的处理
    21      */
    22     @ExceptionHandler({ArithmeticException.class})
    23     public String handlerArithmeticException(Exception ex) {
    24         System.out.println("come a exception:"+ex);
    25         return "error";
    26     }
    27     
    28 }

    3.error.jsp

     1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     2     pageEncoding="ISO-8859-1"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10     <h3>Error page</h3>
    11 </body>
    12 </html>

    4.效果

      

    5.页面显示异常的方式

      @ExceptionHandler方法的入参中不能传入Map,若是希望将异常的信息导入到页面,需要使用ModelAndView方法作为返回值。

     1 package com.spring.it.exception;
     2 
     3 import org.springframework.stereotype.Controller;
     4 import org.springframework.web.bind.annotation.ExceptionHandler;
     5 import org.springframework.web.bind.annotation.RequestMapping;
     6 import org.springframework.web.bind.annotation.RequestParam;
     7 import org.springframework.web.servlet.ModelAndView;
     8 
     9 @Controller
    10 public class ExceptionHandlerDemo {
    11     /**
    12      *异常处理类
    13      */
    14     @RequestMapping("/testExceptionHandlerExceptionResolver")
    15     public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
    16         System.out.println("result="+(10/i));
    17         return "success";
    18     }
    19     
    20     /**
    21      * 异常的处理
    22      */
    23     @ExceptionHandler({ArithmeticException.class})
    24     public ModelAndView handlerArithmeticException(Exception ex) {
    25         System.out.println("come a exception:"+ex);
    26         ModelAndView mv=new ModelAndView("error");
    27         mv.addObject("exception", ex);
    28         return mv;
    29     }
    30     
    31 }

    6.error。jsp

      获取异常信息

     1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     2     pageEncoding="ISO-8859-1"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10     <h3>Error page</h3>
    11     ${exception }
    12 </body>
    13 </html>

    7.效果

      

    8.优先级

      如果出现多个异常的处理方法,走哪一个方法呢?

      是找与异常匹配度更高的处理异常方法。

    9.@ControllerAdvice

      如果在当前的@ExceptionHandler处理当前方法出现的异常,则去由@ControllerAdvice标记的类中查找@ExceptionHandler标记的方法

    结构:

      

    ExceptionHandlerDemo:

     1 package com.spring.it.exception;
     2 
     3 import org.springframework.stereotype.Controller;
     4 import org.springframework.web.bind.annotation.ExceptionHandler;
     5 import org.springframework.web.bind.annotation.RequestMapping;
     6 import org.springframework.web.bind.annotation.RequestParam;
     7 import org.springframework.web.servlet.ModelAndView;
     8 
     9 @Controller
    10 public class ExceptionHandlerDemo {
    11     /**
    12      *异常处理类
    13      */
    14     @RequestMapping("/testExceptionHandlerExceptionResolver")
    15     public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
    16         System.out.println("result="+(10/i));
    17         return "success";
    18     }
    19     
    20     
    21 }

    HandlerException:

     1 package com.spring.it.exception;
     2 
     3 import org.springframework.web.bind.annotation.ControllerAdvice;
     4 import org.springframework.web.bind.annotation.ExceptionHandler;
     5 import org.springframework.web.servlet.ModelAndView;
     6 
     7 @ControllerAdvice
     8 public class HandlerException {
     9     /**
    10      * 异常的处理
    11      */
    12     @ExceptionHandler({ArithmeticException.class})
    13     public ModelAndView handlerArithmeticException(Exception ex) {
    14         System.out.println("come a exception:"+ex);
    15         ModelAndView mv=new ModelAndView("error");
    16         mv.addObject("exception", ex);
    17         return mv;
    18     }
    19     
    20 }

    三:ResponseStatusExceptionResolvler

    1.介绍

      

    2.@ResponseStatus注解的类

    1 package com.spring.it.exception;
    2 
    3 import org.springframework.http.HttpStatus;
    4 import org.springframework.web.bind.annotation.ResponseStatus;
    5 
    6 @ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户名与密码不匹配")
    7 public class UserNameNotMatchPasswordException extends RuntimeException{
    8     private static final long serialVersionUID=1L;
    9 }

    3.处理异常类

     1 package com.spring.it.exception;
     2 
     3 import org.apache.tomcat.util.buf.UEncoder;
     4 import org.springframework.stereotype.Controller;
     5 import org.springframework.web.bind.annotation.ExceptionHandler;
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.bind.annotation.RequestParam;
     8 import org.springframework.web.servlet.ModelAndView;
     9 
    10 @Controller
    11 public class ExceptionHandlerDemo {
    12     /**
    13      *异常处理类,test ExceptionHandlerExceptionResolver
    14      */
    15     @RequestMapping("/testExceptionHandlerExceptionResolver")
    16     public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
    17         System.out.println("result="+(10/i));
    18         return "success";
    19     }
    20     
    21     /**
    22      *异常处理类,test ExceptionHandlerExceptionResolver
    23      */
    24     @RequestMapping("/testResponseStatusExceptionResolver")
    25     public String testResponseStatusExceptionResolver(@RequestParam("i") int i) {
    26         if(i==12) {
    27             throw new UserNameNotMatchPasswordException();
    28         }else {
    29             System.out.println("conmmon execute");
    30         }
    31         return "success";
    32     }
    33     
    34     
    35     
    36 }

    4.效果

      

    四:DefaultHandlerExceptionResolver

    1.介绍

      

    五:SimpleMappingExceptionResolver

    1.介绍

      

    2.处理类

     1 package com.spring.it.exception;
     2 
     3 import org.apache.tomcat.util.buf.UEncoder;
     4 import org.springframework.stereotype.Controller;
     5 import org.springframework.web.bind.annotation.ExceptionHandler;
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.bind.annotation.RequestParam;
     8 import org.springframework.web.servlet.ModelAndView;
     9 
    10 @Controller
    11 public class ExceptionHandlerDemo {
    12     /**
    13      *异常处理类,test ExceptionHandlerExceptionResolver
    14      */
    15     @RequestMapping("/testExceptionHandlerExceptionResolver")
    16     public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i) {
    17         System.out.println("result="+(10/i));
    18         return "success";
    19     }
    20     
    21     /**
    22      *异常处理类,test ExceptionHandlerExceptionResolver
    23      */
    24     @RequestMapping("/testResponseStatusExceptionResolver")
    25     public String testResponseStatusExceptionResolver(@RequestParam("i") int i) {
    26         if(i==12) {
    27             throw new UserNameNotMatchPasswordException();
    28         }else {
    29             System.out.println("conmmon execute");
    30         }
    31         return "success";
    32     }
    33     
    34     /**
    35      *异常处理类,test ExceptionHandlerExceptionResolver
    36      */
    37     @RequestMapping("/testSimpleMappingExceptionResolver")
    38     public String testSimpleMappingExceptionResolver(@RequestParam("i") int i) {
    39         String[] array=new String[10];
    40         String num=array[i];
    41         System.out.println("num:"+num);
    42         return "success";
    43     }
    44     
    45     
    46     
    47 }

    2.效果

      

    3.解决方式

      这个异常可以有SimpleMappingExceptionResolver来处理。

      在xml中注册。

      出现什么异常转到哪一个页面。

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xmlns:context="http://www.springframework.org/schema/context"
     5     xmlns:mvc="http://www.springframework.org/schema/mvc"
     6     xsi:schemaLocation="http://www.springframework.org/schema/beans 
     7     http://www.springframework.org/schema/beans/spring-beans.xsd
     8         http://www.springframework.org/schema/context 
     9         http://www.springframework.org/schema/context/spring-context-4.0.xsd
    10         http://www.springframework.org/schema/mvc 
    11         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    12     <!-- 配置自定义扫描的包 -->               
    13     <context:component-scan base-package="com.spring.it" ></context:component-scan>
    14     
    15     <!-- 配置视图解析器 -->
    16     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    17         <property name="prefix" value="/WEB-INF/views/" />
    18           <property name="suffix" value=".jsp" />
    19     </bean>    
    20     
    21     <mvc:annotation-driven></mvc:annotation-driven>
    22     
    23     <!-- 转换器 -->
    24     <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    25         <property name="converters">
    26             <set>
    27                 <ref bean="employeeConverter"/>
    28             </set>
    29         </property>
    30     </bean>
    31     <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
    32     
    33     <mvc:default-servlet-handler/>
    34     <mvc:annotation-driven ignore-default-model-on-redirect="true"></mvc:annotation-driven>
    35     
    36     <!-- 国家化 -->
    37     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    38         <property name="basename" value="i18n"></property>
    39     </bean>
    40     
    41     <!-- <mvc:view-controller path="/i18n" view-name="i18n"/> -->
    42     <mvc:view-controller path="/i18n2" view-name="i18n2"/>
    43     
    44     <!-- 配置SessionLocaleResolver -->
    45     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
    46     
    47     
    48     <mvc:interceptors>
    49         <!-- 配置自定义拦截器 -->
    50         <bean class="com.spring.it.interceptors.FirstInterceptor"></bean>
    51         <!-- 配置拦截器的作用路径 -->
    52         <mvc:interceptor>
    53             <mvc:mapping path="/emps"/>
    54             <bean class="com.spring.it.interceptors.SecondInterceptor"></bean>
    55         </mvc:interceptor>
    56     
    57         <!-- 配置LocaleChangeInterceter拦截器 -->
    58         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
    59     </mvc:interceptors>
    60     
    61     <!-- 配置CommonsMultipartResolver -->
    62     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    63         <property name="defaultEncoding" value="UTF-8"></property>
    64         <property name="maxUploadSize" value="102400"></property>
    65     </bean>
    66     
    67     <!-- 配置SimpleMappingExceptionResolver来映射异常 -->
    68     <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    69         <property name="exceptionMappings">
    70             <props>
    71                 <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
    72             </props>
    73         </property>
    74     </bean>
    75 </beans>

    4.效果

      

      在页面上可以看到异常的情况。

     

  • 相关阅读:
    和老外交流最常用1000句口语 (一)
    flash自定义右键菜单
    和老外交流最常用1000句口语 (二)
    EBS默认的登录账户和密码
    实例13. 库存补充操作——最小最大计划(MinMax Planning)
    EBS R12常用数据表
    Oracle 软件的行业划分 和 Oracle 公司内部职业划分
    在Org Parameter设置Subinventory Account
    物流(Logistics)的概念
    实例12. 库存补充操作——看板补充(Kanban Replenishment)
  • 原文地址:https://www.cnblogs.com/juncaoit/p/8878182.html
Copyright © 2020-2023  润新知