自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

SpringBoot 接口對參數(shù)進(jìn)行校驗

開發(fā) 架構(gòu)
在 Spring Boot 中,我們可以使用 Java Bean Validation API(JSR 303)來對接口參數(shù)進(jìn)行校驗,該 API 遵循標(biāo)準(zhǔn)的注解格式進(jìn)行參數(shù)校驗。

在 Spring Boot 中,我們可以使用 Java Bean Validation API(JSR 303)來對接口參數(shù)進(jìn)行校驗,該 API 遵循標(biāo)準(zhǔn)的注解格式進(jìn)行參數(shù)校驗。

以下是一些常見的注解:

  • @NotNull:校驗對象是否為 null;
  • @Size(min, max):校驗字符串的長度是否在 min 和 max 之間;
  • @Min:校驗數(shù)字是否大于等于指定值;
  • @Max:校驗數(shù)字是否小于等于指定值;
  • @Email:校驗字符串是否符合 Email 格式。

下面是一個例子,假設(shè)我們有一個用戶注冊接口,需要校驗用戶名和密碼:

@RestController
public class UserController {

@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody @Valid UserDto userDto) {
// 處理用戶注冊請求
return ResponseEntity.ok().build();
}

public static class UserDto {
@NotNull
private String username;

@NotNull
@Size(min = 6, max = 20)
private String password;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}
}

在上面的例子中,我們在 UserDto 類上使用了 @Valid 注解,該注解會告訴 Spring Boot 對該對象進(jìn)行校驗。在 UserDto 類中,我們使用了 @NotNull 和 @Size 注解對 username 和 password 進(jìn)行校驗,保證它們不為 null,且 password 的長度在 6 到 20 之間。

如果校驗失敗,Spring Boot 會拋出MethodArgumentNotValidException 異常,我們可以在 @ExceptionHandler 中捕獲該異常,并返回一個包含錯誤信息的 JSON 響應(yīng),例如:

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult()
.getAllErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return ResponseEntity.badRequest().body(errors);
}
}

在上面的例子中,我們定義了一個全局異常處理器,并在其中捕獲MethodArgumentNotValidException 異常,將校驗失敗的錯誤信息封裝成一個列表并返回。

通過上述方式,我們就可以對接口參數(shù)進(jìn)行校驗,并在校驗失敗時返回錯誤信息,提高接口的健壯性和可靠性。

責(zé)任編輯:姜華 來源: 今日頭條
相關(guān)推薦

2022-12-30 08:49:41

SpringBoot@Validated

2021-11-10 10:03:18

SpringBootJava代碼

2023-11-08 13:33:00

AOP技術(shù)信息

2021-05-18 09:25:54

SpringBoot參數(shù)校驗

2023-11-29 07:23:04

參數(shù)springboto

2024-05-29 08:12:55

接口參數(shù)格式

2023-03-28 08:07:12

2022-03-10 09:00:42

webpack配置項檢驗庫函數(shù)

2022-05-03 10:43:43

SpringJava

2024-06-13 08:19:08

Controller接口參數(shù)

2021-08-10 15:11:27

Spring Boot參數(shù)校驗

2021-08-12 10:32:50

Spring Boot參數(shù)校驗分組校驗

2015-08-28 09:29:37

Volley框架

2009-12-25 09:13:42

ADSL接入網(wǎng)

2025-01-06 09:51:51

2022-11-10 07:53:54

Spring參數(shù)校驗

2020-12-08 08:08:51

Java接口數(shù)據(jù)

2025-02-17 13:23:34

Python同步阻塞MySQL

2022-04-21 09:59:53

Nest參數(shù)校驗

2023-03-06 08:49:02

加密和解密SpringBoot
點贊
收藏

51CTO技術(shù)棧公眾號