日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

springmvc三十:异常处理流程

發布時間:2025/6/15 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springmvc三十:异常处理流程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

handlerExceptionResolvers 異常解析也是springmvc的9大組件之一。

?

DispatcherServlet.properties中默認的異常解析如下:

org.springframework.web.servlet.HandlerExceptionResolver=

? ? org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver 處理@ExceptionHandler
?? ?org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver 處理@ResponseStatus,?@ResponseStatus標注在自定義異常類上
?? ?org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver 判斷是否SpringMVC自帶的異常

?

package com.atchina;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;@Controller public class ExceptionTestController {@RequestMapping("/handler01")public String handler01(Integer i){System.out.println(10/i);return "success";}/*** 告訴SpringMVC這個方法專門處理這個類發生的異常 * 1. 給方法寫一個Exception,接受發生的異常* 2. 返回ModelAndView*/@ExceptionHandler(value={ArithmeticException.class,NullPointerException.class})public ModelAndView handleException01(Exception exception){ModelAndView andView = new ModelAndView("myerror");andView.addObject("ex", exception);return andView;} }

? 全局異常處理類

import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView;// 集中處理所有異常的類加入到ioc容器中 // @ControllerAdvice專門處理異常的類 @ControllerAdvice public class MyGlobalException {@ExceptionHandler(value={ArithmeticException.class,NullPointerException.class})public ModelAndView handleException01(Exception exception){ModelAndView andView = new ModelAndView("myerror");andView.addObject("ex", exception);return andView;} }

?使用HttpStatus

import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus;@ResponseStatus(reason="用戶名不正確", code=HttpStatus.NOT_ACCEPTABLE) public class UserNameNotFoundException extends RuntimeException{private static final long serialVersionUID = 1L;}

? 測試

@RequestMapping("/handler02")public String handler02(@RequestParam("username")String username){if(!"admin".equals(username)){throw new UserNameNotFoundException();}return "success";}

?

總結

以上是生活随笔為你收集整理的springmvc三十:异常处理流程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。