詳解SpringBoot中@NotNull,@NotBlank注解使用
一.添加依賴
<!-- spring-boot 2.3及以上的版本只需要引入下面的依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
二.在類中使用驗證注解
1.創(chuàng)建驗證實體類(嵌套使用)
@Data public class UserDto{ @NotBlank(message = "請輸入用戶名稱") private String userName; @NotBlank(message = "請正確輸入密碼") @Length(min = 6,max = 18) private String password; @Email(message = "請正確輸入郵箱") private String email; @Valid @NotEmpty(message = "角色不能為空") private List<RoleDto> roleDtos; } //被嵌套的類 @Data public class roleDto{ @NotNull(message = "角色ID不能為空") private Integer roleId; @NotBlank(message = "請輸入角色名稱") private String roleName; @NotBlank(message = "請輸入角色名稱") private String roleCode; private String desc; }
2.創(chuàng)建全局異常處理器,對message信息進行處理,并返回給前端
@Component @Slf4j public class GlobalValidHandler implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView()); String errorMsg; if (ex instanceof BindException) { //對于驗證注解在實體類的屬性中的異常處理 BindException bex = (BindException) ex; errorMsg = Objects.requireNonNull(bex.getBindingResult().getFieldError()).getDefaultMessage(); } else if (ex instanceof ConstraintViolationException) { //對于驗證注解直接在方法參數(shù)中使用的異常處理 ConstraintViolationException cve = (ConstraintViolationException) ex; errorMsg = cve.getMessage(); if (errorMsg != null) { errorMsg = errorMsg.substring(errorMsg.indexOf(": ") + 2); } } else { //其他 errorMsg = ex.getMessage(); } modelAndView.addObject("msg", errorMsg); modelAndView.addObject("code", HttpServletResponse.SC_BAD_REQUEST); return modelAndView; } }
3.在controller中的使用
@RestController @RequestMapping("/user") public class UserController{ @Autowired private UserService userService; @PostMapping("/add") public ApiResult addUser(@Valid @RequsetBody UserDto userDto){ return ApiResult.data(userService.addUser(userDto)); } }
三.在方法參數(shù)中使用驗證注解,與@RequsetParam注解同時使用,注意類上使用@Validated
@Validated @RestController @RequestMapping("/user") public class UserController{ @Autowired private UserSerivce userService; @GetMapping("/list") public ApiResult queryUsers(@RequestParam(name="userName", required = false, defaultValue = "") @NotBlank(message = "請輸入用戶") String userName, @RequestParam(name="pageNumber", required = false, defaultValue = 1) Integre pageNumber, @RequestParam(name="pageSize", required = false, defaultValue = 10) Integre pageSize){ return ApiResult.Data(userService.queryUsers(userName,pageNumber,pageSize)); } }
ps: 需要在全局變量中對驗證注解進行異常處理 GlobalValidHandler
四.自定義驗證注解
1.定義驗證注解
@Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = MyConstraintValidtor.class) public @interface MyValidator { String message() default "校驗未通過"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
2.實現(xiàn)驗證注解的具體驗證邏輯
public class MyConstraintValidator implements ConstraintValidator<MyValidator, Object> { @Override public void initialize(MyValidator validator) { ConstraintValidator.super.initialize(validator); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { //具體校驗邏輯 //........ //........ //舉個例 驗證不為空 return !ObjectUtils.isEmpty(value); } }
3.使用
@Data public class UserDto{ @NotNull(message="用戶名不能為空") private String userName; @MyValidator(message="密碼不能為空") private String password; }
到此這篇關(guān)于詳解SpringBoot中@NotNull,@NotBlank注解使用的文章就介紹到這了,更多相關(guān)SpringBoot注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)之常見排序算法(下)
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)之常見排序算法(下),與之相對有(上),想了解的朋友可以去本網(wǎng)站掃搜,在這兩篇文章里涵蓋關(guān)于八大排序算法的所有內(nèi)容,需要的朋友可以參考下2023-01-01eclipse/intellij idea 遠程調(diào)試hadoop 2.6.0
這篇文章主要介紹了eclipse/intellij idea 遠程調(diào)試hadoop 2.6.0的相關(guān)資料,需要的朋友可以參考下2016-07-07spring整合atomikos實現(xiàn)分布式事務(wù)的方法示例
本文整合了一個spring和atomikos的demo,并且通過案例演示說明atomikos的作用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05SpringBoot整合Security權(quán)限控制登錄首頁
這篇文章主要為大家介紹了SpringBoot整合Security權(quán)限控制登錄首頁示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11