SoFunction
Updated on 2025-03-08

Introduction and usage examples of Java verification validate

Java verification validate

In daily development, we often need to provide reliable API interfaces. At this time, the requested entry parameters need to be checked to ensure the correctness of the final data entry, which has become an indispensable task. For example, when a user registers, he will verify the correctness of the mobile phone format, the correctness of the email format, the password is not weak password, etc.

However, if you use if-else code to verify, there are many places where verification is needed, and the code volume will become very bloated. If a class request parameter verification field is increased, I believe you will not be happy. It is definitely not appropriate to do this, and the code is not elegant. So how to solve this problem?

The answer is the validation to be introduced below

Introduction to validation

Validation technology is first used in Java. In 2009, Java officially proposed the Bean Validation specification, and then experienced three changes in standards such as JSR303, JSR349, and JSR380, and developed to 2.0.

Bean Validation, like the JPA we have learned before, only provides specifications and not specific implementations. Therefore, in actual use, the verification component of hibernate is commonly used: -validator

Common Notes

Generally speaking, under the package, a series of constraint annotations are defined, with a total of 22 annotations, so just skip them quickly. as follows:

Empty and non-empty checks

  • @NotBlank: Only used for strings not null, and the string .trim() after length must be greater than 0.
  • @NotEmpty: The element of the collection object is not 0, that is, the collection is not empty.
  • @NotNull: Cannot be null .
  • @Null: Must be null .

Numerical check

  • @DecimalMax(value): The annotated element must be a number, and its value must be less than or equal to the specified maximum value.
  • @DecimalMin(value): The annotated element must be a number, and its value must be greater than or equal to the specified minimum value.
  • @Digits(integer, fraction): The annotated element must be a number and its value must be within an acceptable range.
  • @Positive: judge positive numbers.
  • @PositiveOrZero: judges positive number or 0.
  • @Max(value): The value of this field can only be less than or equal to this value.
  • @Min(value): The value of this field can only be greater than or equal to this value.
  • @Negative: judge negative numbers.
  • @NegativeOrZero: judges negative numbers or 0.

Boolean value check

  • @AssertFalse: The annotated element must be true .
  • @AssertTrue: The annotated element must be false .

Length check

  • @Size(max, min): Check whether the size of the field is between min and max, which can be a string, array, collection, Map, etc.

Date check

  • @Future: The annotated element must be a future date.
  • @FutureOrPresent: determines whether a date is a future or present date.
  • @Past: Check that the date of this field is in the past.
  • @PastOrPresent: determines whether a date is a past or present date.

Other checks

  • @Email: The annotated element must be an email address.
  • @Pattern(value): The annotated element must comply with the specified regular expression.

Hibernate Validator The additional constraint annotation is defined under the package. Common ones are shown.

  • @Range(min=, max=): The annotated element must be within the appropriate range.
  • @Length(min=, max=): The size of the annotated string must be within the specified range.
  • @URL(protocol=,host=,port=,regexp=,flags=): The commented string must be a valid URL.
  • @SafeHtml: determine whether the submitted HTML is safe. For example, javascript scripts cannot be included, etc.

I won’t list the others one by one. If you are interested, you can go to the source code package to check it out.

@Valid and @Validated

  • @Valid annotation is defined by Bean Validation. It can be added to ordinary methods, constructor methods, method parameters, method returns, and member variables to indicate that they need to be subject to constraint verification.
  • @Validated annotation is a Spring Validation lock definition, which can be added to classes, method parameters, and ordinary methods, indicating that they need to be subject to constraint verification. At the same time, @Validated has a value attribute, which supports group verification.

For beginners, it's easy to confuse the @Valid and @Validated annotations.

  • ① Declarative verification: Spring Validation only annotates @Validated to implement declarative verification.
  • ② Group verification: The @Valid annotation provided by Bean Validation, because there is no attribute for group verification, group verification cannot be provided. At this point, we can only use the @Validated annotation.
  • ③ Nested verification: In comparison, there are more [member variables] in @Valid annotation. This results in that if there are nested objects, you can only use @Valid annotation.

In the spring-boot-starter-web dependency, the hibernate-validator dependency has been introduced by default, so this example uses Hibernate Validator as the implementation framework of Bean Validation.

1. Simple verification

Write entity classes (here is a scenario where commonly used user registration is taken as a scenario)

@Data
public class SysUser {
    private Long userId;
    /**
      * account
      */
    @NotBlank(message = "Username cannot be empty")
    @Size(min = 6, message = "The username cannot be less than 6 characters")
    private String username;
    /**
      * password
      */
    @NotEmpty(message = "Password cannot be empty")
    @Size(min = 8, message = "The password length cannot be less than 8 characters")
    private String password;
    /**
      * Phone number
      */
    @NotBlank(message = "The mobile phone number cannot be empty")
    @Size(min = 11, max = 11, message = "The mobile phone number is incorrect")
    private String mobile;
}

Writing a front-end controller

@RestController
@RequestMapping("/user")
public class SysUserController {
    @PostMapping("/add")
    public R addUser(@RequestBody @Valid SysUser sysUser) {
        ("Walk here to indicate the verification is successful");
        (sysUser);
        return (R.SUCCESS_MSG);
    }
}

Write front-end response encapsulation entity

public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;
    public static final String SUCCESS_MSG = "The operation was successful!";
    public static final String FAIL_MSG = "The operation failed!";
    public R() {
        ((String) "code", 0);
    }
    public static R error() {
        return error(500, "Unknown exception, please contact the administrator");
    }
public static R error(String msg) { return error(500, msg); } public static R error(int code, String msg) { R r = new R(); ((String) "code", code); ((String) "msg", msg); return r; } public static R ok(String msg) { R r = new R(); ((String) "msg", msg); return r; } public static R ok(Object object) { R r = new R(); ("result", object); return r; } public static R ok(int code, String msg) { R r = new R(); ((String) "code", code); ((String) "msg", msg); return r; } public static R ok(Map<String, Object> map) { R r = new R(); (map); return r; } public static R ok() { return new R(); } public R put(String key, Object value) { (key, value); return this; } 

Write custom exceptions (for subsequent business throw exception errors)

public class RRException extends RuntimeException {

private static final long serialVersionUID = 1L;

private String msg;

private int code = 500;

public RRException(String msg) {

super(msg);

 = msg;

}

public RRException(String msg, Throwable e) {

super(msg, e);

 = msg;

}

public RRException(String msg, int code) {

super(msg);

 = msg;

 = code;

}

public RRException(String msg, int code, Throwable e) {

super(msg, e);

 = msg;

 = code;

}

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

 = msg;

}

public int getCode() {

return code;

}

public void setCode(int code) {

 = code;

}

}

When accessing the post interface /user/add, if the parameters do not meet the definition in the Model, the program will throw back the 400 exception status code and prompt an error message, as shown below.

{
“timestamp”: “2021-05-20T01:08:28.831+0000”,
“status”: 400,
“error”: “Bad Request”,
“errors”: [
{
“codes”: [ “”, “”, “”, “Size” ],
“arguments”: [ { “codes”: [ “”, “mobile” ], “arguments”: null, “defaultMessage”: “mobile”, “code”: “mobile” },
11,
11
],
“defaultMessage”: “The phone number is incorrect”,
“objectName”: “sysUser”,
“field”: “mobile”,
“rejectedValue”: “155833013”,
“bindingFailure”: false,
“code”: “Size”
}
],
“message”: “Validation failed for object=‘sysUser'. Error count: 1”,
“path”: “/user/add”
}

Custom verification annotations

Although JSR303 and Hibernate Validtor have provided many verification annotations, they still cannot meet our requirements when facing complex parameter verification. At this time, we need to customize verification annotations.

Below is a custom verification annotation with "The List array cannot contain null elements" as an instance

1. The annotation definition is shown.

@Target({ElementType.ANNOTATION_TYPE, , })

@Retention(RUNTIME)

@Documented

@Constraint(validatedBy = )//The annotation implementation class is specified here
public @interface ListNotHaveNull {

/**

 * Adding the value attribute can be used as a condition during verification. If not required, the definition here can be removed.

 /

 int value() default 0;

 String message() default "The List collection cannot contain null elements";

 Class<?>[] groups() default {};

 Class<? extends Payload>[] payload() default {};

 /*

 * Define List, in order to add multiple sets of rules to one property of the Bean

 */

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})

@Retention(RUNTIME)

@Documented

@interface List {

ListNotHaveNull[] value();

}

}

Write a custom verification implementation class

@Service
public class ListNotHaveNullValidatorImpl implements ConstraintValidator&lt;ListNotHaveNull, List&gt; {
private int value;
@Override
public void initialize(ListNotHaveNull constraintAnnotation) {
//Passing in value value can be used in verification = ();
}
public boolean isValid(List list, ConstraintValidatorContext constraintValidatorContext) {
for (Object object : list) {
if (object == null) {
//If the List collection contains Null elements, the verification failsreturn false;
} else if (object instanceof String) {
String value = ();
if (().length() == 0){
return false;
}
}
}
return true;
}
}

Add annotations to the model:

@Data
public class SysRole {
private Long roleId; @NotBlank(message = "The character name cannot be empty") private String name; @NotEmpty(message = "Resource list cannot be empty") @ListNotHaveNull(message = "List cannot contain null elements") @Valid private List&amp;lt;String&amp;gt; paths; 

Writing a front-end controller

@PostMapping(“/addRole”)

public R addRole(@RequestBody @Valid SysRole sysRole) {

(“Let's go here to indicate the verification is successful”);

(sysRole);

return (R.SUCCESS_MSG);

}

The usage method is the same as "simple verification". Just add @Valid to the Model that needs to be checked.

Common Validtor verification tool class

public class ValidatorUtils {
private ValidatorUtils() { }
private static Validator validator; static { validator = ().getValidator(); } /** * Verification object * * @param object Object Object to be Verification * @param groups Groups to be Verification * @throws RRException If the verification fails, an RRException exception will be reported */ public static void validateEntity(Object object, Class&amp;lt;?&amp;gt;... groups) throws RRException { Set&amp;lt;ConstraintViolation&amp;lt;Object&amp;gt;&amp;gt; constraintViolations = (object, groups); if (!()) { Iterator&amp;lt;ConstraintViolation&amp;lt;Object&amp;gt;&amp;gt; iterator = (); StringBuilder msg = new StringBuilder(); while (()) { ConstraintViolation&amp;lt;Object&amp;gt; constraint = (); (()).append(','); } throw new RRException(().substring(0,().lastIndexOf(','))); } } 

How to use, after receiving the parameters passed by the front end, use ([parameter name]); to verify, and support group verification. The group needs to define the packet interface.

Summarize

This is the article about the introduction and use of Java verification validate. For more related Java verification validate content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!