springMVC?@RestControllerAdvice注解使用方式
使用 @RestControllerAdvice 的主要場景包括:
- 全局異常處理:處理所有控制器中拋出的未捕獲異常。
- 數(shù)據(jù)校驗失敗處理:處理 Bean Validation 校驗失敗的情況。
- 自定義響應(yīng):統(tǒng)一定義響應(yīng)格式或錯誤信息。
@RestControllerAdvice 注解的類通常與以下組件結(jié)合使用:
@ExceptionHandler:用于處理特定的異常類型。@ResponseStatus:用于定義異常的HTTP狀態(tài)。@ExceptionHandler方法可以訪問異常對象、請求對象(WebRequest)、響應(yīng)對象等,以構(gòu)造合適的響應(yīng)。
以下是一個簡單的示例,演示如何使用 @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) {
// 構(gòu)造錯誤信息
String error = "An error occurred: " + ex.getMessage();
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
// 可以添加更多的異常處理方法
}在這個示例中,GlobalExceptionHandler 類使用 @RestControllerAdvice 注解標(biāo)記,使其成為全局異常處理器。類中的 handleCustomException 方法使用 @ExceptionHandler 注解標(biāo)記,用于處理 CustomException 類型的異常。
使用 @RestControllerAdvice 可以集中處理異常,使控制器代碼更簡潔、更專注于業(yè)務(wù)邏輯,同時提高異常處理的可維護(hù)性。
一個模擬權(quán)限校驗的案例
首先自定義一個權(quán)限不夠的異常
public class PermissionException extends Exception{
// 構(gòu)造函數(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","錯誤,沒有權(quán)限");
return msg;
}
}然后寫一個處理權(quán)限校驗的攔截器
/*
* 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)聽到,最終給客戶端返回沒有權(quán)限
到此這篇關(guān)于springMVC @RestControllerAdvice注解使用方式的文章就介紹到這了,更多相關(guān)springMVC @RestControllerAdvice注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring中@PropertySource注解使用場景解析
這篇文章主要介紹了Spring中@PropertySource注解使用場景解析,@PropertySource注解就是Spring中提供的一個可以加載配置文件的注解,并且可以將配置文件中的內(nèi)容存放到Spring的環(huán)境變量中,需要的朋友可以參考下2023-11-11
Spring的RedisTemplate存儲的key和value有特殊字符的處理
這篇文章主要介紹了Spring的RedisTemplate存儲的key和value有特殊字符的處理方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
關(guān)于集合和字符串的互轉(zhuǎn)實現(xiàn)方法
下面小編就為大家?guī)硪黄P(guān)于集合和字符串的互轉(zhuǎn)實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
spring aop action中驗證用戶登錄狀態(tài)的實例代碼
本篇文章主要介紹了spring aop action中驗證用戶登錄狀態(tài)的實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07

