Data verification is one of the necessary functions of a complete Web project. Some FRONT-END JS verification can only deal with the data input on the portal site, but if someone bypassing the browser directly using some HTTP simulation tools to send some illegal data to the background server, it will cause errors and even crash of the program. For example, the server sends illegal data such as incorrect time format mailbox format to the background database. Therefore, it is necessary to verify the new data on the server.
Recently through online video to understand and study the validation of the spring data verifier, below I will demonstrate the validation data validator code, interested friends can look at.
Import validation related JARS
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> < version > 6.0.21. Final < / version > < / dependency > <! -- Validator data verification is complete -->Copy the code
The relevant code
import com.zhoukai.common.Constant; import com.zhoukai.exception.BussiException; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; /** * @description * @author Mr.ZHOU * @date Created in 2021/5/9 12:59 */ public class ValidatorUtil {private final static Validator validator; / * * * build validator * / static {the validator = Validation. BuildDefaultValidatorFactory (.) getValidator (); } @param param */ public static void validata(Object param){/** * Set is null */ set <ConstraintViolation<Object>> errors = validator.validate(param); If (errors! = null){ for (ConstraintViolation<Object> error : errors) { String message = error.getMessage(); Throw new BussiException(constant. VALIDETOR_ERROR_CODE,message); }}}}Copy the code