preface

The text has been included in my GitHub warehouse, welcome Star: https://github.com/bin392328206/six-finger to plant a tree is the best time ten years ago, the second is I know a lot of people don’t play qq now, but the nostalgia, welcome to join six pulse excalibur Java novice learning group, group number: 549684836 encourages you to blog on the tech road

omg

This thing should be one of the most commonly used components of our masturbation business, because before the small 66 is their own is according to use, also did not say a comprehensive understanding of this piece, today small 66 will take you to comb through ha.

JSR – 303

Jsr-303 is a sub-specification in JavaEE 6 called Bean Validation, and the official reference implementation is Hibernate Validator. This implementation has nothing to do with Hibernate ORM. Jsr-303 is used to validate the values of fields in Java beans. Spring MVC 3.x also has strong support for JSR-303, which allows easy validation of form submission data using annotations in the controller. Spring 4.0 is starting to support Bean Validation. Jsr-303 Basic verification rules

Empty check

  • @null Verifies whether an object is Null
  • @notnull verifies that the object is NotNull. Strings of length 0 cannot be checked
  • @notBlank checks whether the constraint string is Null and whether the trimmed length is greater than 0, only for strings, and strips whitespace
  • @notempty checks whether the constraint element is NULL or EMPTY

Boolean check

  • @assertTrue Verifies whether a Boolean object is true
  • @AssertFalse Verifies whether a Boolean object is false

The length of the check

@size (min=, Max =) Verifies that the Length of the object (Array, Collection, Map, String) is within the specified range. @length (min=, Max =) Verifies that the Length of the String is between min and Max

Date of inspection

  • @past verifies that Date and Calendar objects precede the current time. If this is true, the annotated element must be a Past Date
  • @future verifies that Date and Calendar objects are after the current time. If this is true, the annotated element must be a Future Date

Regular inspection

@pattern Verifies that the String complies with regular expression rules. The annotated elements comply with specified regular expressions. -regexp: regular expression -flags: specifies the array of pattern. Flag, indicating the options related to the regular expression

Numerical check

Note: This parameter is recommended for String and Integer, but not for int, because the form value “” cannot be converted to int, but can be converted to String as” “and Integer as null

  • @min verifies that Number and String objects are large or equal to the specified value
  • @max verifies that Number and String objects are equal to the specified value
  • @decimalMax The annotated value must not be greater than the maximum specified in the constraint. The parameter to this constraint is a string representation of the maximum value defined by BigDecimal. Fractional existence accuracy
  • @decimalmin The annotated value must be no less than the minimum specified in the constraint. The argument to this constraint is a string representation of the minimum value defined by BigDecimal. Fractional existence accuracy
  • @digits Verifies that the Number and String are valid
  • @digits (integer=,fraction=) verifies that the string is a number in the specified format, integer specifies integer precision, and fraction specifies decimal precision
  • @range (min=, Max =) The specified element must be within the appropriate Range
  • @ Range (min = 10000, Max = 50000, message = “Range. Bean. The wage”)
  • If the associated object is a collection or array, the elements are recursively checked. If the associated object is a map, the values are recursively checked.
  • @creditCardNumber Credit card verification
  • @email Checks whether the Email address is null. If the Email address is null, the authentication is successful
  • @ScriptAssert(lang= ,script=, alias=)
  • @URL(protocol=,host=, port=,regexp=, flags=)

use

As for the use of words, small 66 side is not one example, I believe that everyone should be, may not have so detailed understanding at ordinary times, so this time I am to review for everyone

@Data
public class User {
 
 /** id */
 @NotNull(message="Id cannot be empty")
 private Long id;  / * * name * / @NotBlank(message="Name cannot be empty.")  private String name;  / * * * / age @NotNull(message="Age cannot be empty.")  @Max(message="Can't be more than 120 years old.", value = 120)  @Min(message="Must not be less than one year old.", value = 1)  private Integer age;  /** Create time */ @Future  private Date createTime; }  Copy the code

And then in the Controller layer, I’ll just call it Valid

/ * ** If the verification fails, throw an exception directly  * @param user
  * @return
* / @PostMapping("/test1")  public Object test1(@RequestBody @Valid User user) {  return "Operation successful!";  } Copy the code

Three ways to perform Validation for Spring Validation

The first is to add an @valid annotation to the Controller method argument to throw an exception if the check fails

Call will throw an org. Springframework. Web. Bind. MethodArgumentNotValidException anomaly:

The 2019-04-21 11:35:28. 600 WARN 10852 - [nio - 8080 - exec - 4] W.S.M.S.D efaultHandlerExceptionResolver: Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failedfor argument [0] in public java.lang.Object com.example.validation.UserController.test1(com.example.validation.User) with 3 errors: [Field error in object 'user' on field 'createTime': rejected value [Mon Dec 31 08:00:00 CST 2018]; codes [Future.user.createTime,Future.createTime,Future.java.util.Date,Future]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.createTime,createTime]; arguments []; default message [createTime]]; Default message [need to be a future time]] [Field errorin object 'user' on field 'age': rejected value [0]; codes [Min.user.age,Min.age,Min.java.lang.Integer,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.age,age]; arguments []; default message [age],1]; Default message [age cannot be less than 1 year old]] [Field errorin object 'user' on field 'name': rejected value []; codes [NotBlank.user.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name]]; Default message [name cannot be empty]]]Copy the code

In fact, like this, I think you have to work with the global unified exception, which is actually pretty good, and that’s what I’m doing so far. Recommended rating: 3 stars

The second option is to add an @VALID annotation before the Controller method parameter and define a BindingResult parameter after the parameter

/ * ** Put the verification result into BindingResult, and the user can decide and process it  * @param user
  * @param bindingResult
  * @return
* / @PostMapping("/test2")  public Object test2(@RequestBody @Valid User user, BindingResult bindingResult) { // Check parameters if (bindingResult.hasErrors()) {  String messages = bindingResult.getAllErrors()  .stream()  .map(ObjectError::getDefaultMessage)  .reduce((m1, m2) -> m1 + ";" + m2)  .orElse("Incorrect parameter input!");  throw new IllegalArgumentException(messages);  }   return "Operation successful!";  Copy the code

Encapsulate the result in a BindingResult, and then encapsulate the information to be thrown by itself. This is also possible, except for each controller. Less applicable, 2 stars is recommended

Validation.builddefault ValidatorFactory().getValidator().validate(XXX)

/ * ** The user manually invokes the corresponding API to perform verification  * @param user
  * @return
* / @PostMapping("/test3")  public Object test3(@RequestBody User user) { // Check parameters validate(user);   return "Operation successful!";  }   private void validate(@Valid User user) {  Set<ConstraintViolation<@Valid User>> validateSet = Validation.buildDefaultValidatorFactory()  .getValidator()  .validate(user, new Class[0]);  if(! CollectionUtils.isEmpty(validateSet)) { String messages = validateSet.stream()  .map(ConstraintViolation::getMessage)  .reduce((m1, m2) -> m1 + ";" + m2)  .orElse("Incorrect parameter input!");  throw new IllegalArgumentException(messages);   } } Copy the code

The principle is similar, but it looks the same, not as elegant, with a 2 star recommendation

At the end

In fact, the principle of these three uses is the same, but the use of the form is not the same, in fact, it depends on your own, haha.

reference

  • JSR

Daily for praise

Ok, everybody, that’s all for this article, you can see people here, they are real fans.

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article

Six pulse excalibur | article “original” if there are any errors in this blog, please give criticisms, be obliged!