Pay attention to “an ape small talk” public friends are clear, in the Tanabata dog abuse day, we combined with the previous actual combat project, launched “Tanabata, take you born a validation framework”, born together with an API parameter verification wheel.


The wheel can make the research and development personnel, no longer entangled in parameter verification, through simple configuration can complete verification; Free up more time to write business code; Fully achieve verification and business stripping.


All right, let’s keep it low-key. No flattery. Hibernate Validator is another commonly used parameter verification framework. Please prepare a small bench to start our sharing.


1.

Is what?

First flip out a picture to exercise your observation skills.



As you can see from the above figure, data validation runs through all application layers (from presentation to persistence), and often the same validation logic is implemented at each layer, which can be time-consuming and error-prone.


Then throw another picture, welcome everyone to find fault (combined with the previous picture).



We will find that to avoid repeated data validation at each level, we can bundle the validation logic directly into the domain model, confusing the domain class with the validation code.


That’s interesting. You might be a little confused. Don’t worry! You simply want to add validation rules to your entity-class attributes, but how do you add validation rules?


Jsr380-bean Validation 2.0 does not define the metadata model and API for entity and method Validation. What is JSR380?


In order to see the heart again later not false, we explain again.


JSR is an important standard in the Java world. It stands for Java Specification Requests, or Java Specification Requests. Anyone can submit a JSR to add new apis and services to the Java platform.


Jsr380-bean Validation 2.0 is a new data Validation specification defined in Java.


Having said that, only the specification is not implemented and everything is bullshit. Don’t worry, it’s time for Hibernate Validator, our pig’s foot.


What exactly is a Hibernate Validator? Hibernate Validator is an implementation of the JSR 380 data validation specification.


At this point, you should know more or less about JSR, JSR 380, Hibernate Validator.


All right, all talk and no work that’s a code farmer’s rascal, and it’s time to get real.


2.

How to use?



Step 1: Introduce dependency packages. Don’t worry about it. It’s over.

<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> < version > 6.0.17. Final < / version > < / dependency > < the dependency > < groupId > org. Anyone < / groupId > < artifactId > javax.mail. El < / artifactId > < version > 3.0.1 - b09 < / version > < / dependency > < the dependency > < the groupId > org. Hibernate < / groupId > < artifactId > hibernate validator - cdi < / artifactId > < version > 6.0.17. The Final < / version > </dependency> </dependencies>Copy the code


Step 2: Define the login request object and add the verification rule. Focus on the annotations, So easy!!

import javax.validation.constraints.*;

public class UserLoginRequest {

    @NotNull(message = "[interface version number] cannot be empty!")
    @Pattern(regexp = "^(\\d+)(\\.\\d+)? $", message = "[interface version number] format is wrong!")
    @Size(min = 0, max = 4, message = "The [interface version number] length is incorrect. The maximum length is [{Max}]!")
    private String versionNo;

    @NotNull(message = "[Phone number] cannot be empty!")
    @Size(min = 0, max = 11, message = "[User's mobile number] length is incorrect. The maximum length is [{Max}]!")
    private String mobile;

    @NotNull(message = "[Order number] cannot be empty!")
    @Size(min = 0, max = 32, message = "[Order number] length error, maximum length [{Max}]!")
    private String orderId;

    @NotNull(message = "[verification code] cannot be empty!")
    @Size(min = 0, max = 6, message = "[verification code] length error, maximum length [{Max}]!") private String smsCode; //TODO provides the setter/getter... . }Copy the code



Step 3: according to the convention, should write a test class, run to see, this time let’s step into place, directly package the tool class. Can be directly taken to a real project to practice, absolutely useful.

import javax.validation.*;
import java.util.*;

public class ValidateUtil {

    public static  void validate(T t) {
        if (null == t) {
            throw new ValidateException("E0001"."Parameter null");
        }

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set> constraintViolations = validator.validate(t);

        List errorList = new ArrayList();
        for (ConstraintViolation constraintViolation : constraintViolations) {
            errorList.add(constraintViolation.getMessage());
        }
        if(! errorList.isEmpty()) { throw new ValidateException("E9999", errorList.toString()); }}}Copy the code


Step 4: Customize the exception. This is contingent on the situation, not required.

public class ValidateException extends RuntimeException { private String code; private String msg; /** * public ValidateException(String code, String MSG) {super(MSG); this.setCode(code); this.setMsg(msg); } //TODO provides the setter/getter... . }Copy the code



Step 5: Run and see if it stands the test.

public class App {
    public static void main(String[] args) {
        UserLoginRequest request = new UserLoginRequest();
        request.setVersionNo("abc"); // The version number is incorrect request.setmobile ("138013800000"); Try {ValidateUtil. Validate (request); } catch (ValidateException e) {//TODO obtains the exception code and returns the exception information to the front end. System.out.println(string.format ())"code: %s, msg:%s",e.getCode(),e.getMsg())); }}}Copy the code


The sixth step: the result analysis, see the result, really meet the expectation: the length of the mobile phone number is wrong, the format of the interface version number is wrong, other parameter values are blank.


3.

There’s no end to the technology. The rest is up to you, but mastering the above is enough to get you through the project.


Ok, pass the regular army type share + last troops on the type of sharing, believe you will certainly can win API parameters calibration, also can concentrate on to write business code, if you has not yet come into contact with these before, might as well take practice, big probability significantly improve your r&d efficiency, make more time to drink coffee, happiness rise abruptly.

Recommended reading:

Tanabata, take you to give birth to a verification framework

This tech sunflower gem is really hardcore