SpringBoot如何使用@RequestBody進(jìn)行數(shù)據(jù)校驗(yàn)
SpringBoot 如何使用 @RequestBody 進(jìn)行數(shù)據(jù)校驗(yàn)
什么是 @RequestBody
@RequestBody 注解用于接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 Java 對象。它的作用是將 HTTP 請求正文中的 JSON 字符串綁定到相應(yīng)的 Java 對象上。在 SpringBoot 中,我們通常使用 @RequestBody 注解來接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 Java 對象。
如何使用 @RequestBody 進(jìn)行數(shù)據(jù)校驗(yàn)
在 SpringBoot 中,我們可以使用 JSR-303 規(guī)范提供的注解來對 Java 對象進(jìn)行數(shù)據(jù)校驗(yàn)。JSR-303 是 Java EE 6 中引入的 Bean Validation 規(guī)范,它提供了一套用于數(shù)據(jù)校驗(yàn)的注解。
在 SpringBoot 中使用 JSR-303 注解進(jìn)行數(shù)據(jù)校驗(yàn)的步驟如下:
- 引入相關(guān)依賴
在 pom.xml 文件中添加以下依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
- 在 Java Bean 中添加校驗(yàn)注解
在 Java Bean 中添加校驗(yàn)注解,例如:
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ù)校驗(yàn),@RequestBody 注解用于接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 User 對象。
- 處理校驗(yàn)結(jié)果
如果數(shù)據(jù)校驗(yàn)失敗,會拋出 MethodArgumentNotValidException 異常。我們可以在 ControllerAdvice 中捕獲此異常,并返回校驗(yàn)結(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 異常,并處理校驗(yàn)結(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 進(jìn)行數(shù)據(jù)校驗(yàn)的完整代碼示例。 ### 引入依賴 在 pom.xml 文件中添加以下依賴: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
編寫實(shí)體類
@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ù)校驗(yàn),@RequestBody 注解用于接收前臺發(fā)送的 JSON 數(shù)據(jù),并將其轉(zhuǎn)化為 User 對象。
編寫全局異常處理類
如果數(shù)據(jù)校驗(yàn)失敗,會拋出 MethodArgumentNotValidException 異常。我們可以在 ControllerAdvice 中捕獲此異常,并返回校驗(yàn)結(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 異常,并處理校驗(yàn)結(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 請求,并驗(yàn)證數(shù)據(jù)校驗(yàn)的結(jié)果是否符合預(yù)期。
總結(jié)
在 SpringBoot 中使用 @RequestBody 進(jìn)行數(shù)據(jù)校驗(yàn),可以有效地提高代碼的健壯性和可靠性。通過 JSR-303 提供的注解,我們可以輕松地對 Java 對象進(jìn)行數(shù)據(jù)校驗(yàn),并在數(shù)據(jù)校驗(yàn)失敗時返回相應(yīng)的錯誤信息。希望本文能夠?qū)Υ蠹以?SpringBoot 中使用 @RequestBody 進(jìn)行數(shù)據(jù)校驗(yàn)有所幫助。
以上就是SpringBoot 如何使用 @RequestBody 進(jìn)行數(shù)據(jù)校驗(yàn)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot @RequestBody數(shù)據(jù)校驗(yàn)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
如何基于FTP4J實(shí)現(xiàn)FTPS連接過程解析
這篇文章主要介紹了如何基于FTP4J實(shí)現(xiàn)FTPS連接過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10SpringBoot框架aop切面的execution表達(dá)式解讀
這篇文章主要介紹了SpringBoot框架aop切面的execution表達(dá)式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05使用javaweb項(xiàng)目對數(shù)據(jù)庫增、刪、改、查操作的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于使用javaweb項(xiàng)目對數(shù)據(jù)庫增、刪、改、查操作的實(shí)現(xiàn)方法,avaWeb是指使用Java語言進(jìn)行Web應(yīng)用程序開發(fā)的技術(shù),可以利用Java編寫一些動態(tài)網(wǎng)頁、交互式網(wǎng)頁、企業(yè)級應(yīng)用程序等,需要的朋友可以參考下2023-07-07spring boot實(shí)現(xiàn)阿里云視頻點(diǎn)播上傳視頻功能(復(fù)制粘貼即可)
這篇文章主要介紹了spring boot實(shí)現(xiàn)阿里云視頻點(diǎn)播上傳視頻功能(復(fù)制粘貼即可),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12