IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

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

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

一、简介

• 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/?p=13903


Warning: A non-numeric value encountered in /data/wangzhan/tech.souyunku.com.wp/wp-content/themes/dux/functions-theme.php on line 1154
赞(95) 打赏



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

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码
IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

评论 抢沙发

大前端WP主题 更专业 更方便

联系我们联系我们

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

微信扫一扫打赏


Fatal error: Uncaught Exception: Cache directory not writable. Comet Cache needs this directory please: `/data/wangzhan/tech.souyunku.com.wp/wp-content/cache/comet-cache/cache/https/tech-souyunku-com/index.q`. Set permissions to `755` or higher; `777` might be needed in some cases. in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php:367 Stack trace: #0 [internal function]: WebSharks\CometCache\Classes\AdvancedCache->outputBufferCallbackHandler() #1 /data/wangzhan/tech.souyunku.com.wp/wp-includes/functions.php(5109): ob_end_flush() #2 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(303): wp_ob_end_flush_all() #3 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(327): WP_Hook->apply_filters() #4 /data/wangzhan/tech.souyunku.com.wp/wp-includes/plugin.php(470): WP_Hook->do_action() #5 /data/wangzhan/tech.souyunku.com.wp/wp-includes/load.php(1097): do_action() #6 [internal function]: shutdown_action_hook() #7 {main} thrown in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php on line 367