SpringBoot如何使用@RequestBody進行數(shù)據(jù)校驗
SpringBoot 如何使用 @RequestBody 進行數(shù)據(jù)校驗
什么是 @RequestBody
@RequestBody 注解用于接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 Java 對象。它的作用是將 HTTP 請求正文中的 JSON 字符串綁定到相應的 Java 對象上。在 SpringBoot 中,我們通常使用 @RequestBody 注解來接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 Java 對象。
如何使用 @RequestBody 進行數(shù)據(jù)校驗
在 SpringBoot 中,我們可以使用 JSR-303 規(guī)范提供的注解來對 Java 對象進行數(shù)據(jù)校驗。JSR-303 是 Java EE 6 中引入的 Bean Validation 規(guī)范,它提供了一套用于數(shù)據(jù)校驗的注解。
在 SpringBoot 中使用 JSR-303 注解進行數(shù)據(jù)校驗的步驟如下:
- 引入相關(guān)依賴
在 pom.xml 文件中添加以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>- 在 Java Bean 中添加校驗注解
在 Java Bean 中添加校驗注解,例如:
public class User {
@NotNull(message = "用戶名不能為空")
private String username;
@NotNull(message = "密碼不能為空")
@Size(min = 6, message = "密碼長度不能小于 6 位")
private String password;
// 省略 getter 和 setter 方法
}- 在 Controller 方法中添加 @Validated 和 @RequestBody 注解
在 Controller 方法中添加 @Validated 和 @RequestBody 注解,例如:
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/add")
public Result addUser(@Validated @RequestBody User user) {
// 處理添加用戶的邏輯
}
}在上述代碼中,@Validated 注解用于啟用數(shù)據(jù)校驗,@RequestBody 注解用于接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 User 對象。
- 處理校驗結(jié)果
如果數(shù)據(jù)校驗失敗,會拋出 MethodArgumentNotValidException 異常。我們可以在 ControllerAdvice 中捕獲此異常,并返回校驗結(jié)果。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result handleValidationException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> errorMessages = new ArrayList<>();
for (ObjectError error : allErrors) {
errorMessages.add(error.getDefaultMessage());
}
return Result.error(String.join(",", errorMessages));
}
}在上述代碼中,我們使用 @RestControllerAdvice 注解聲明一個全局異常處理類,其中 @ExceptionHandler 注解用于捕獲 MethodArgumentNotValidException 異常,并處理校驗結(jié)果,最終返回一個 Result 對象。
完整代碼示例
@Data
public class User {
@NotNull(message = "用戶名不能為空")
private String username;
@NotNull(message = "密碼不能為空")
@Size(min = 6, message = "密碼長度不能小于 6 位")
private String password;
}
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/add")
public Result addUser(@Validated @RequestBody User user) {
// 處理添加用戶的邏輯
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result handleValidationException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> errorMessages = new ArrayList<>();
for (ObjectError error : allErrors) {
errorMessages.add(error.getDefaultMessage());
}
return Result.error以上示例代碼可能有些不完整,我們來完整展示一下如何使用 @RequestBody 進行數(shù)據(jù)校驗的完整代碼示例。
### 引入依賴
在 pom.xml 文件中添加以下依賴:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>編寫實體類
@Data
public class User {
@NotNull(message = "用戶名不能為空")
private String username;
@NotNull(message = "密碼不能為空")
@Size(min = 6, message = "密碼長度不能小于 6 位")
private String password;
}編寫 Controller
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/add")
public Result addUser(@Validated @RequestBody User user) {
// 處理添加用戶的邏輯
}
}在上述代碼中,@Validated 注解用于啟用數(shù)據(jù)校驗,@RequestBody 注解用于接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 User 對象。
編寫全局異常處理類
如果數(shù)據(jù)校驗失敗,會拋出 MethodArgumentNotValidException 異常。我們可以在 ControllerAdvice 中捕獲此異常,并返回校驗結(jié)果。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result handleValidationException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> errorMessages = new ArrayList<>();
for (ObjectError error : allErrors) {
errorMessages.add(error.getDefaultMessage());
}
return Result.error(String.join(",", errorMessages));
}
}在上述代碼中,我們使用 @RestControllerAdvice 注解聲明一個全局異常處理類,其中 @ExceptionHandler 注解用于捕獲 MethodArgumentNotValidException 異常,并處理校驗結(jié)果,最終返回一個 Result 對象。
編寫啟動類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}編寫測試類
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void addUserTest() {
User user = new User();
user.setUsername("test");
user.setPassword("12345");
ResponseEntity<Result> responseEntity = restTemplate.postForEntity("/user/add", user, Result.class);
Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
Result result = responseEntity.getBody();
Assert.assertEquals(ResultStatus.FAIL.getCode(), result.getStatus());
Assert.assertEquals("密碼長度不能小于 6 位", result.getMessage());
}
}在上述代碼中,我們使用 SpringBoot 自帶的 TestRestTemplate 對象來模擬發(fā)送 POST 請求,并驗證數(shù)據(jù)校驗的結(jié)果是否符合預期。
總結(jié)
在 SpringBoot 中使用 @RequestBody 進行數(shù)據(jù)校驗,可以有效地提高代碼的健壯性和可靠性。通過 JSR-303 提供的注解,我們可以輕松地對 Java 對象進行數(shù)據(jù)校驗,并在數(shù)據(jù)校驗失敗時返回相應的錯誤信息。希望本文能夠?qū)Υ蠹以?SpringBoot 中使用 @RequestBody 進行數(shù)據(jù)校驗有所幫助。
以上就是SpringBoot 如何使用 @RequestBody 進行數(shù)據(jù)校驗的詳細內(nèi)容,更多關(guān)于SpringBoot @RequestBody數(shù)據(jù)校驗的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java調(diào)用高德地圖API根據(jù)詳細地址獲取經(jīng)緯度詳細教程
寫了一個經(jīng)緯度相關(guān)的工具,分享給有需求的小伙伴們,下面這篇文章主要給大家介紹了關(guān)于Java調(diào)用高德地圖API根據(jù)詳細地址獲取經(jīng)緯度,文中通過圖文以及代碼介紹的非常詳細,需要的朋友可以參考下2024-04-04
Java 將文件轉(zhuǎn)為字節(jié)數(shù)組知識總結(jié)及實例詳解
這篇文章主要介紹了Java 將文件轉(zhuǎn)為字節(jié)數(shù)組實例詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12
elasticsearch?java客戶端action的實現(xiàn)簡單分析
這篇文章主要為大家介紹了elasticsearch?java客戶端action的實現(xiàn)簡單分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04
Java如何實現(xiàn)實體類轉(zhuǎn)Map、Map轉(zhuǎn)實體類
這篇文章主要介紹了Java 實現(xiàn)實體類轉(zhuǎn)Map、Map轉(zhuǎn)實體類的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

