springMVC?@RestControllerAdvice注解使用方式
使用 @RestControllerAdvice
的主要場景包括:
- 全局異常處理:處理所有控制器中拋出的未捕獲異常。
- 數(shù)據(jù)校驗失敗處理:處理 Bean Validation 校驗失敗的情況。
- 自定義響應:統(tǒng)一定義響應格式或錯誤信息。
@RestControllerAdvice
注解的類通常與以下組件結合使用:
@ExceptionHandler
:用于處理特定的異常類型。@ResponseStatus
:用于定義異常的HTTP狀態(tài)。@ExceptionHandler
方法可以訪問異常對象、請求對象(WebRequest
)、響應對象等,以構造合適的響應。
以下是一個簡單的示例,演示如何使用 @RestControllerAdvice
:
java
import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @RestControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { // 處理自定義異常 @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex, WebRequest request) { // 構造錯誤信息 String error = "An error occurred: " + ex.getMessage(); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } // 可以添加更多的異常處理方法 }
在這個示例中,GlobalExceptionHandler
類使用 @RestControllerAdvice
注解標記,使其成為全局異常處理器。類中的 handleCustomException
方法使用 @ExceptionHandler
注解標記,用于處理 CustomException
類型的異常。
使用 @RestControllerAdvice
可以集中處理異常,使控制器代碼更簡潔、更專注于業(yè)務邏輯,同時提高異常處理的可維護性。
一個模擬權限校驗的案例
首先自定義一個權限不夠的異常
public class PermissionException extends Exception{ // 構造函數(shù) public PermissionException() { super(); } public PermissionException(String message) { super(message); } public PermissionException(String message, Throwable cause) { super(message, cause); } public PermissionException(Throwable cause) { super(cause); } }
然后用注解的方式寫一個異常處理類
@RestControllerAdvice public class PermissionExceptionHandler { @ExceptionHandler(PermissionException.class) public Map handleMyCustomException(PermissionException ex) { Map<String, String> msg = new HashMap<>(); msg.put("status","500"); msg.put("msg","錯誤,沒有權限"); return msg; } }
然后寫一個處理權限校驗的攔截器
/* * preHandle在執(zhí)行處理器方法之前執(zhí)行 * postHandle在執(zhí)行處理器方法之后執(zhí)行 * afterCompletion在這次請求完成后執(zhí)行 * */ @Component public class PermissionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String auth = request.getParameter("auth"); System.out.println(auth); if ("0".equals(auth)){ throw new PermissionException(); } //返回true放行,返回false不放行 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
然后把攔截器注冊到spring中
@Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private HandlerInterceptor permissionInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(permissionInterceptor) .addPathPatterns("/**") // 攔截所有請求 .excludePathPatterns("/ignoreThis"); // 排除不需要攔截的請求 } }
然后你請求http://localhost:8080/user/1?auth=1
你會發(fā)現(xiàn)auth=1的時候攔截器放行
auth=0的時候會被攔截器攔截,并且拋出我們自定義的異常,然后自定義異常會被我們寫的異常處理器監(jiān)聽到,最終給客戶端返回沒有權限
到此這篇關于springMVC @RestControllerAdvice注解使用方式的文章就介紹到這了,更多相關springMVC @RestControllerAdvice注解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring中@PropertySource注解使用場景解析
這篇文章主要介紹了Spring中@PropertySource注解使用場景解析,@PropertySource注解就是Spring中提供的一個可以加載配置文件的注解,并且可以將配置文件中的內容存放到Spring的環(huán)境變量中,需要的朋友可以參考下2023-11-11Spring的RedisTemplate存儲的key和value有特殊字符的處理
這篇文章主要介紹了Spring的RedisTemplate存儲的key和value有特殊字符的處理方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12spring aop action中驗證用戶登錄狀態(tài)的實例代碼
本篇文章主要介紹了spring aop action中驗證用戶登錄狀態(tài)的實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07