十一(一)、springMVC之异常处理@ExceptionHandler注解

一、概述:

springMVC通过HandlerExceptionResolver处理程序的异常,异常包括 Handler映射、数据绑定以及目标方法执行时发生的异常;

springMVC提供的HandlerExceptionResolver的实现类有:

  1. ExceptionHandler:处理异常,可以把异常写到页面上;
  2. DefaultHandlerExceptionResplver 处理指定异常;
  3. ResponseStatusExceptionResource 更改自定义异常的状态码和异常原因
  4. simpleMappingExceptionResolver 指定异常跳转页面

 

ExceptionHandler:

@ExceptionHandler注解:

1.在@ExceptionHandler 方法的入参中可以加入Exception 类型的参数,该参数即对应发生的异常的对象 

2.在@ExceptionHandler 方法的入参不能传入 map;若希望吧异常信息传到页面上,需要使用ModelAndView做返回值

3.@ExceptionHandler 存在优先级为,从小到大;越匹配优先级越高;

4.@ControllerAdvice:如果当前Handler中找不到@ExceptionHandler,则去@ControllerAdvice标记的类中查找@ExceptionHandler标记的方法来处理异常

1.目录结构为:

2.配置:

web.xml配置:只配置了DispatcherServlet

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 4     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 5     id="WebApp_ID" version="3.1">
 6     <servlet>
 7         <servlet-name>springDispatcherServlet</servlet-name>
 8         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 9         <!-- 配置DispatcherServletd 一个初始化参数:配置springmvc配置文件的位置和名称 -->
10         <!-- 实际上也可以不通过 contextConfigLocation 来配置Springmvc的配置文件,而是用默认的 即默认的配置文件为 
11             /WEB-INF/<servlet-name>-servlet.xml 本项目默认位置配置文件即为: /WEB-INF/springDispatcherServlet-servlet.xml -->
12         <init-param>
13             <param-name>contextConfigLocation</param-name>
14             <param-value>classpath:spring.xml</param-value>
15         </init-param>
16         <!-- 表示springDispatcherServlet在加载的时候被创建 -->
17         <load-on-startup>1</load-on-startup>
18     </servlet>
19 
20     <!-- Map all requests to the DispatcherServlet for handling -->
21     <servlet-mapping>
22         <servlet-name>springDispatcherServlet</servlet-name>
23         <url-pattern>/</url-pattern>
24     </servlet-mapping>
25 </web-app>
View Code

 spring.xmp配置:基础配置

基础配置包括:包扫描的配置、视图解析器配置、<mvc:annotation-driven></mvc:annotation-driven>;

 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:mvc="http://www.springframework.org/schema/mvc"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 9 
10     <context:component-scan base-package="handler"></context:component-scan>
11     <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
12     <bean
13         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
14         <property name="prefix" value="/WEB-INF/views/"></property>
15         <property name="suffix" value=".jsp"></property>
16     </bean>
17         
18     <mvc:annotation-driven></mvc:annotation-driven>
19     
20 </beans>
View Code

3.EceptionController.java

  • 方法的入参中可以加入Exception 类型的参数,该参数即对应发生的异常的对象
  • 异常信息传到页面上,需要使用ModelAndView做返回值
 1 package handler;
 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 @RequestMapping("/emp")
10 @Controller
11 public class EceptionController {
12 
13     @RequestMapping("/testError")
14     public String testError(@RequestParam("i") int i) {
15         System.out.println(10 / i);
16         return "success";
17     }
18 
19     @ExceptionHandler({ ArithmeticException.class })
20     public ModelAndView handleArithmeticException(Exception ex) {
21         System.out.println("出异常了:" + ex);
22         ModelAndView md = new ModelAndView("error");
23         md.addObject("ex", ex);
24         return md;
25     }
26 }

4.success.jsp&&error.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 success
11 </body>
12 </html>
View Code
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 <h4>Error Page</h4>
11 ${ex}
12 </body>
13 </html>
View Code

5.运行结果:

当访问:http://localhost:8080/DataOperate/emp/testError?i=10时,页面跳转到success页面;当访问http://localhost:8080/DataOperate/emp/testError?i=0时,访问了error页面,且error页面打印了异常信息;

 

6.如果异常不匹配:

也就是说@ExceptionHandler标记的异常和实际抛出的异常不匹配,如下,比如EceptionController.java中异常时算术异常,但是@ExceptionHandler标记的只有运行时异常:那么异常存在优先级为,从小到大;越匹配优先级越高;

 1 package handler;
 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 @RequestMapping("/emp")
10 @Controller
11 public class EceptionController {
12 
13     @RequestMapping("/testError")
14     public String testError(@RequestParam("i") int i) {
15         System.out.println(10 / i);
16         return "success";
17     }
18 
19     @ExceptionHandler({ RuntimeException.class })
20     public ModelAndView handleRuntimeException(Exception ex) {
21         System.out.println("【出异常了]:" + ex);
22         ModelAndView md = new ModelAndView("error");
23         md.addObject("ex", ex);
24         return md;
25     }
26 }

此时,访问;http://localhost:8080/DataOperate/emp/testError?i=0,也会跳转到error页面且显示异常信息同上图,且控制台打印:

【出异常了]:java.lang.ArithmeticException: / by zero

 

7.如果当前Handler中找不到@ExceptionHandler

@ControllerAdvice:如果当前Handler中找不到@ExceptionHandler,则去@ControllerAdvice标记的类中查找@ExceptionHandler标记的方法来处理异常

EceptionController.java

 1 package handler;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RequestParam;
 6 
 7 @RequestMapping("/emp")
 8 @Controller
 9 public class EceptionController {
10 
11     @RequestMapping("/testError")
12     public String testError(@RequestParam("i") int i) {
13         System.out.println(10 / i);
14         return "success";
15     }
16 }

ExceptionHandlerProcess.java

 1 package handler;
 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 ExceptionHandlerProcess {
 9 
10     @ExceptionHandler({ ArithmeticException.class })
11     public ModelAndView handleArithmeticException(Exception ex) {
12         System.out.println("出异常了:" + ex);
13         ModelAndView md = new ModelAndView("error");
14         md.addObject("ex", ex);
15         return md;
16     }
17 
18     @ExceptionHandler({ RuntimeException.class })
19     public ModelAndView handleRuntimeException(Exception ex) {
20         System.out.println("【出异常了]:" + ex);
21         ModelAndView md = new ModelAndView("error");
22         md.addObject("ex", ex);
23         return md;
24     }
25 
26 }

运行结果:

此时,访问;http://localhost:8080/DataOperate/emp/testError?i=0,也会跳转到error页面且显示异常信息同上图,且控制台打印相关信息:

    出异常了:java.lang.ArithmeticException: / by zero

posted @ 2022-03-19 17:15  啄木鸟伍迪  阅读(1219)  评论(0编辑  收藏  举报
//火箭 GenerateContentList();