做便民工具網(wǎng)站怎么樣百度問(wèn)答兼職怎么做
1. 使用Hibernate Validator進(jìn)行注解校驗(yàn)
這是Java中最常用的參數(shù)校驗(yàn)方式,基于JSR 303/JSR 380規(guī)范的實(shí)現(xiàn),通常結(jié)合@Valid
或@Validated
注解進(jìn)行參數(shù)校驗(yàn)。
使用步驟:
- 添加依賴(如果使用Spring Boot,通常已經(jīng)內(nèi)置了Hibernate Validator):
<dependency><groupId>org.hibernate.validator</groupId><artifactId>hibernate-validator</artifactId>
</dependency>
- 在DTO類中使用校驗(yàn)注解:
public class UserDTO {@NotNull(message = "用戶名不能為空")@Size(min = 3, max = 20, message = "用戶名長(zhǎng)度必須在3到20之間")private String username;@Email(message = "郵箱格式不正確")private String email;// 其他字段和getter/setter
}
- 在Controller中使用
@Valid
或@Validated
來(lái)觸發(fā)校驗(yàn):
@PostMapping("/user")
public ResponseEntity<String> createUser(@Valid @RequestBody UserDTO userDTO) {// 如果校驗(yàn)失敗,會(huì)自動(dòng)拋出異常return ResponseEntity.ok("用戶創(chuàng)建成功");
}
- 如果需要自定義異常處理,可以在全局異常處理器中處理
MethodArgumentNotValidException
:
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {Map<String, String> errors = new HashMap<>();ex.getBindingResult().getAllErrors().forEach(error -> {String fieldName = ((FieldError) error).getField();String errorMessage = error.getDefaultMessage();errors.put(fieldName, errorMessage);});return ResponseEntity.badRequest().body(errors);
}
2. 手動(dòng)校驗(yàn)
對(duì)于復(fù)雜的業(yè)務(wù)邏輯,可能需要手動(dòng)編寫(xiě)校驗(yàn)邏輯??梢酝ㄟ^(guò)Java代碼在Controller或Service層進(jìn)行參數(shù)的業(yè)務(wù)校驗(yàn)。
if (userDTO.getUsername() == null || userDTO.getUsername().length() < 3) {throw new IllegalArgumentException("用戶名長(zhǎng)度必須大于3");
}
3. 自定義注解
如果Hibernate Validator內(nèi)置的注解不能滿足需求,可以自定義校驗(yàn)注解。比如,創(chuàng)建一個(gè)自定義注解來(lái)驗(yàn)證某個(gè)字段是否滿足自定義規(guī)則。
自定義注解示例:
- 創(chuàng)建注解:
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
public @interface CustomConstraint {String message() default "默認(rèn)錯(cuò)誤信息";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};
}
- 創(chuàng)建校驗(yàn)邏輯:
public class CustomValidator implements ConstraintValidator<CustomConstraint, String> {@Overridepublic void initialize(CustomConstraint constraintAnnotation) {}@Overridepublic boolean isValid(String value, ConstraintValidatorContext context) {// 自定義校驗(yàn)邏輯return value != null && value.startsWith("A");}
}
- 在DTO類中使用自定義注解:
public class UserDTO {@CustomConstraint(message = "用戶名必須以A開(kāi)頭")private String username;
}
4. Spring的@RequestParam
和@PathVariable
校驗(yàn)
對(duì)于簡(jiǎn)單的請(qǐng)求參數(shù),可以在方法參數(shù)中使用@RequestParam
和@PathVariable
結(jié)合Hibernate Validator注解進(jìn)行校驗(yàn)。
@GetMapping("/user/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable @NotNull(message = "用戶ID不能為空") Long id) {// 獲取用戶邏輯
}