springboot 参数格式校验操作

时间:2022-09-05 00:14:31

springboot 参数格式校验

@Validated

字面意思校验

springboot 参数格式校验操作

@RequestBody

该注解不用多说,意思是接收为json格式的参数

@Validated

字面意思校验, 需要配合@NotBlank 或者 @NotNull 注解才能生效

进入到请求体参数中。

springboot 参数格式校验操作

springboot 参数注解校验

1.添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-validation</artifactId>
  4. </dependency>
  1. package com.xl.annotation;
  2. import lombok.Data;
  3. import org.hibernate.validator.constraints.Length;
  4. import org.hibernate.validator.constraints.Range;
  5. import javax.validation.constraints.*;
  6. import java.math.BigDecimal;
  7. import java.util.Date;
  8. @Data
  9. public class User {
  10.  
  11. @NotNull(message = "ID不能为空")
  12. @Range(min = 1, max = 100, message = "ID必须在1到100之间")
  13. private Integer id;
  14.  
  15. @NotNull(message = "姓名不能为空")
  16. @Length(min = 2, max = 6, message = "姓名必须在2到6位之间")
  17. private String name;
  18.  
  19. @NotNull(message = "余额不能为空")
  20. @DecimalMax(value = "30.50", message = "余额不能超过30.5")
  21. @DecimalMin(value = "1.50", message = "余额不能低于1.5")
  22. private BigDecimal amount;
  23.  
  24. @NotNull(message = "生日不能为空")
  25. @Past(message = "生日必须是过去")
  26. private Date birthday;
  27.  
  28. @NotBlank(message = "邮箱不能为空")
  29. @Email(message = "邮箱格式不正确")
  30. private String email;
  31.  
  32. @NotBlank(message = "手机号不能为空")
  33. @Pattern(regexp = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$", message = "手机号格式错误")
  34. private String phone;
  35. }

2.controller层

  1. package com.xl.annotation;
  2. import io.swagger.annotations.Api;
  3. import io.swagger.annotations.ApiOperation;
  4. import io.swagger.annotations.ApiParam;
  5. import org.springframework.validation.BindingResult;
  6. import org.springframework.validation.ObjectError;
  7. import org.springframework.validation.annotation.Validated;
  8. import org.springframework.web.bind.annotation.*;
  9. import javax.validation.ValidationException;
  10. import javax.validation.constraints.Max;
  11. import javax.validation.constraints.NotNull;
  12.  
  13. @RestController
  14. @Validated
  15. @Api(value = "手机验证",description = "手机验证")
  16. public class MobileController {
  17. @ApiOperation("手机验证")
  18. @RequestMapping("/phone")
  19. public String mobilePattern( Phone phone){
  20. return "chengg";
  21. }
  22. @PostMapping("/getUser")
  23. @ApiOperation("手机验证12")
  24. public String getUserStr( @NotNull(message = "name 不能为空")@RequestParam String name,
  25. @Max(value = 99, message = "不能大于99岁")@RequestParam Integer age) {
  26. return "name: " + name + " ,age:" + age;
  27. }
  28. /* @PostMapping("/getUser1")
  29. @ApiOperation("手机验证c")
  30. public String getUser(@RequestBody @Validated User user, BindingResult bindingResult) {
  31. validData(bindingResult);
  32. return "name: " + user.getName() + " ,age:" + user.getAge();
  33. }*/
  34. private void validData(BindingResult bindingResult) {
  35. if (bindingResult.hasErrors()) {
  36. StringBuffer sb = new StringBuffer();
  37. for (ObjectError error : bindingResult.getAllErrors()) {
  38. sb.append(error.getDefaultMessage());
  39. }
  40. throw new ValidationException(sb.toString());
  41. }
  42. }
  43.  
  44. @PostMapping("/test")
  45. @ApiOperation(value = "测试", notes = "")
  46. public String test(@ApiParam(name = "test", value = "参数", required = true) @Validated @RequestBody User test, BindingResult bindingResult) {
  47. validData(bindingResult);
  48. if(bindingResult.hasErrors()){
  49. String errorMsg = bindingResult.getFieldError().getDefaultMessage();
  50. return errorMsg;
  51. }
  52. return "参数验证通过";
  53. }
  54. }

3.自定义一个抛出异常类

  1. package com.xl.annotation;
  2. import org.springframework.http.HttpStatus;
  3. import org.springframework.web.bind.annotation.ExceptionHandler;
  4. import org.springframework.web.bind.annotation.ResponseStatus;
  5. import org.springframework.web.bind.annotation.RestControllerAdvice;
  6. import javax.validation.ConstraintViolation;
  7. import javax.validation.ConstraintViolationException;
  8. import javax.validation.ValidationException;
  9. import java.util.Set;
  10.  
  11. /**
  12. * 自定义验证抛出异常
  13. */
  14. @RestControllerAdvice
  15. public class GlobalExceptionHandler {
  16. @ExceptionHandler(ValidationException.class)
  17. @ResponseStatus(HttpStatus.BAD_REQUEST)
  18. public String handle(ValidationException exception) {
  19. if(exception instanceof ConstraintViolationException){
  20. ConstraintViolationException exs = (ConstraintViolationException) exception;
  21.  
  22. Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
  23. for (ConstraintViolation<?> item : violations) {
  24. //打印验证不通过的信息
  25. System.out.println(item.getMessage());
  26. }
  27. }
  28. return exception.getMessage();
  29. }
  30. }

4.加一个当检测第一个参数不合法时立即返回错误不会继续进行校验

  1. package com.xl.annotation;
  2. import org.hibernate.validator.HibernateValidator;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import javax.validation.Validation;
  6. import javax.validation.Validator;
  7. import javax.validation.ValidatorFactory;
  8.  
  9. @Configuration
  10. public class ValidatorConf {
  11. @Bean
  12. public Validator validator() {
  13. ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
  14. .configure()
  15. .failFast( true )
  16. .buildValidatorFactory();
  17. Validator validator = validatorFactory.getValidator();
  18. return validator;
  19. }
  20. }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/taiguolaotu/article/details/118336396