专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

Spring MVC 教程(十三)异常处理

一、简介

• Spring MVC 通过 HandlerExceptionResolver 处理程序的异常,包括 Handler 映射、数据绑定以及目标方法执行时发生的异常。
• SpringMVC 提供的 HandlerExceptionResolver 的实现类

• DispatcherServlet 默认装配的 HandlerExceptionResolver :
– 没有使用 配置:

72_1.png

– 使用了 配置:

72_2.png

二、ExceptionHandlerExceptionResolver

在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
@ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
@ExceptionHandler 方法标记的异常有优先级的问题.
@ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常, 则将去 @ControllerAdvice 标记的类中查找@ExceptionHandler 标记的方法来处理异常.

1、 编写异常handle

     @ExceptionHandler({RuntimeException.class})
     public ModelAndView handleArithmeticException2(Exception ex){
         System.out.println("[出异常了]: " + ex);
         ModelAndView mv = new ModelAndView("error");
         mv.addObject("exception", ex);
         return mv;
     }

     ////优先级高于handleArithmeticException2,如果没有找到具体的异常就使用handleArithmeticException2
     @ExceptionHandler({ArithmeticException.class})
     public ModelAndView handleArithmeticException(Exception ex){
         System.out.println("出异常了: " + ex);
         ModelAndView mv = new ModelAndView("error");
         mv.addObject("exception", ex);
         return mv;
     }

     @RequestMapping("/testExceptionHandlerExceptionResolver")
     public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
         System.out.println("result: " + (10 / i));
         return "success";
     }

2、在jsp页面发送请求

 <a href="testExceptionHandlerExceptionResolver?i=0">Test ExceptionHandlerExceptionResolver</a>

3、 编写错误回显的页面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>

     <h4>Error Page</h4>

     ${requestScope.exception }

 </body>
 </html>

72_3.png

备注:

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

 @ControllerAdvice
 public class SpringMVCTestExceptionHandler {

     @ExceptionHandler({ArithmeticException.class})
     public ModelAndView handleArithmeticException(Exception ex){
         System.out.println("----> 出异常了: " + ex);
         ModelAndView mv = new ModelAndView("error");
         mv.addObject("exception", ex);
         return mv;
     }

 }

三、ResponseStatusExceptionResolver

在异常及异常父类中找到 @ResponseStatus 注解,然后使用这个注解的属性进行处理。

1、定义一个 @ResponseStatus 注解修饰的异常类

 @ResponseStatus(value=HttpStatus.FORBIDDEN, reason="用户名和密码不匹配!")
 public class UserNameNotMatchPasswordException extends RuntimeException{

     /**
      * 
      */
     private static final long serialVersionUID = 1L;

 }

2、编写handle

使用@ResponseStatus标注的方法即使没有异常也会报异常

 @ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND)
     @RequestMapping("/testResponseStatusExceptionResolver")
     public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
         if(i == 13){
             throw new UserNameNotMatchPasswordException();
         }
         System.out.println("testResponseStatusExceptionResolver...");

         return "success";
     }

3、在jsp页面发送请求

 <a href="testResponseStatusExceptionResolver?i=13">Test ResponseStatusExceptionResolver</a>

使用@ResponseStatus标注的方法即使没有异常也会报异常

72_4.png

72_5.png

四、DefaultHandlerExceptionResolver

对一些特殊的异常进行处理,比如NoSuchRequestHandlingMethodException、HttpRequestMethodNotSupportedException、HttpMediaTypeNotSupportedException、HttpMediaTypeNotAcceptableException等

1、编写handle

 @RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
     public String testDefaultHandlerExceptionResolver(){
         System.out.println("testDefaultHandlerExceptionResolver...");
         return "success";
     }

2、在jsp页面发送请求

 <a href="testDefaultHandlerExceptionResolver">Test DefaultHandlerExceptionResolver</a>

72_6.png

五、SimpleMappingExceptionResolver

如果希望对所有异常进行统一处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常

1、 在springmvc.xml配置SimpleMappingExceptionResolver,配置异常的名字exceptionAttribute和异常回显的页面exceptionMappings


 <!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
     <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
         <property name="exceptionAttribute" value="ex"></property>
         <property name="exceptionMappings">
             <props>
                 <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
             </props>
         </property>
     </bean>    

2、 编写handle

 @RequestMapping("/testSimpleMappingExceptionResolver")
     public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
         String [] vals = new String[10];
         System.out.println(vals[i]);
         return "success";
     }

3、在jsp页面发送请求

 <a href="testSimpleMappingExceptionResolver?i=12">Test SimpleMappingExceptionResolver</a>

4、错误回显页面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>

     <h4>Error Page</h4>

     ${requestScope.ex }

 </body>
 </html>

72_7.png

https://www.cnblogs.com/leeSmall/category/1093236.html

文章永久链接:https://tech.souyunku.com/13903

未经允许不得转载:搜云库技术团队 » Spring MVC 教程(十三)异常处理

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们