日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

springmvc三十:异常处理流程

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

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這個方法專門處理這個類發(fā)生的異常 * 1. 給方法寫一個Exception,接受發(fā)生的異常* 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";}

?

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。