Recently in refactoring the old project code, found that the check-in parameter occupies a lot of code, before I know this piece of knowledge is limited to using stringutils and other tools to judge multiple if blocks, the code is not a problem, but always write these annoying, after all, write code to pay attention to elegance, So I studied the Java EE Api on the check class, basically overturned my previous understanding of the calibration annotations and so on, here to record the results.
@NotNull
The @NotBlank
@NotEmpty
differences between the three annotations and the use
@NotNull
: The check-in parameter cannot be null, a string with a length of 0 is not correctly checked or a string that is completely blank
@NotBlank
: Contains @NotNull
the ability to verify that the string contents are empty
@NotEmpty
: Checks whether the incoming collection is empty
When the above annotations are not satisfied, an exception is thrown and the default message content is printed.
age not be null
the error message such as this
If you want to customize the error message, you can @NotNull(message = "信息不能为空")
define
@Valid
The use
If the entry is an object and you want to verify that the object content is correct, you will use several annotations in section 1,
However, there is a problem at this point: if you do not use @Valid
annotations, the annotations in section 1 do not take effect during the entry process, and are only validated when saved (not excluding the case of the PO and DTO being the same object)
Of course, there is a big premise, that is, there is no other way to enter the compared with his test execution.
* * So if it's simple to get the exception to be reported instead of just returning it, you can use only@Valid
Handling of custom checksums and error messages
(1) Use Bindingresult
object to receive @Valid
checksum error message
/** * Use Bindingresult with @valid * Get the error message with a partial stack */@PostMapping ("/validationtest6") public String V AlidationTest6 (@RequestBody @Valid User user, bindingresult result) {if (result.ha Serrors ()) {//Fetch an error message Objecterror next = Result.getallerrors (). iterator (). Next (); Log.error ("error={}", next); You can return the error message by yourself or you can customize the return next.tostring (); }//do somethings return "verification pass"; }/** * Use Bindingresult with @valid to get the error message */@PostMapping ("/validationtest7") public String valid ATIONTEST7 (@RequestBody @Valid User user, bindingresult result) {if (Result.haserr ORS ()) {//Fetch an error message Objecterror next = Result.getallerrors (). iterator (). Next (); String defaultmessage = Next.getdefaultmessage (); Log.error ("error={}", Defaultmessage); You can return your own error message or customize it. return defaultmessage; }//do somethings return "verification pass"; }
(2) Using validator object, not trust in @Valid
the implementation
/** * 使用Validator未抽取工具类时的实现 */ @PostMapping("/validationTest9") public String validationTest9(@RequestBody User user){ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<User>> validate = validator.validate(user); if(!validate.isEmpty()){ ConstraintViolation<User> next = validate.iterator().next(); String message = next.getMessage(); log.error("error={}",message); return message; } //do somethings return "校验通过"; }
The above gives you two methods, the second one looks more code, in fact, this should be no use @Valid
of the problem, because you do not know @Valid
how the annotation checksum error code. Almost less efficient.
Below for you to provide a tool class, respectively, to provide the top two ways of encapsulation, if you only want to use the BindingResult
way, then large can remove the code that is not used
Packaged tool classes and use
(1) Tool class code
Package Com.cnblogs.hellxz.myutils;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.validation.bindingresult;import Org.springframework.validation.objecterror;import Javax.validation.constraintviolation;import Javax.validation.validation;import Javax.validation.Validator;import Javax.validation.validatorfactory;import java.util.set;/** * <b> class name </b>: Validatorutils * <p><b > Description </b> Check in Parameter </p> * * <p><b> creation date </b>: 8/24/18 12:54 PM </p> * * @author HELLXZ Zhang * @version 1.0 * @since JDK 1.8 */public class Validatorutils {private static final Logger log = Loggerfactory.getlo Gger (Validatorutils.class); private static final Validator Validator; static {Validatorfactory factory = Validation.builddefaultvalidatorfactory (); Validator = Factory.getvalidator (); }/** * Grouping for check or full check * difference is whether to pass groups class * PS: The advantage of grouping is that the same dto is very useful when assigning different checksum parameters to different methods. * There is no need to rewrite a new same fieldDTO Specifies the operation of different check fields, more flexible * @param Object-checked DTO objects * @param groups grouping class, either an interface or a class, only as an identity * @return The result you want to return. public static <T> String validentity (Final T object, Class ... groups) {set<constraintviolation<t>& Gt violations = Validator.validate (object, groups); if (!violations.isempty ()) {//This only takes the first error to prevent too many parameters being returned constraintviolation<t> violation = violation S.iterator (). Next (); Log.error (Violation.getmessage ()); The following code can also return "{\" "code\": \ "400\", \ "msg\": \ "" + violation.getmessage () + "\"} "by using the returned tool class that is used by the company or the individual. } return null; }/** * Verifies that a property of a parameter object satisfies the requirements, skips other checks, supports grouping * @param object-checked Dto Object * @param property name within PropertyName Dto Object * @pa RAM Groups Group name * @return Checksum error returned results */public static <T> string Validproperty (Final T object, String Prope Rtyname, Class ... groups) {set<constraintviolation<t>> violations = Validator.validateproperty (object, PropertyName, groups); if (!violations.isempty ()) {//This only takes the first error to prevent too many parameters being returned constraintviolation<t> violation = violation S.iterator (). Next (); Log.error (Violation.getmessage ()); The following code can also return "{\" "code\": \ "400\", \ "msg\": \ "" + violation.getmessage () + "\", using the Returned tool class that is used by the company or individual "}"; } return null; }/** * using Bindingresult with @valid annotations implements the tool class * @param result bindingresult Object * @return Result String */public s Tatic String validentity (bindingresult result) {if (Result.haserrors ()) {//Fetch an error message Objecterror Next = Result.getallerrors (). iterator (). Next (); String defaultmessage = Next.getdefaultmessage (); Log.error ("error={}", Defaultmessage); You can return the error message by yourself or you can customize return "{\" code\ ": \" 400\ ", \" msg\ ": \" "+ Defaultmessage +" \ "}"; } return null; }}
(2) Use of the tool class
private static Logger log = Loggerfactory.getlogger (Validatecontroller.class); /** * Check the user object annotation within Group A check */@PostMapping ("/validationtest1") public String validationTest1 (@RequestBody user User) {String valid = validatorutils.validentity (user, a.class); if (null! = valid) return valid; Do somethings return "verification pass"; }/** * Check the user object annotations within Group B for the checksum */@PostMapping ("/validationtest2") public String ValidationTest2 (@RequestBody User user) {String valid = validatorutils.validentity (user, b.class); if (null! = valid) return valid; Do somethings return "verification pass"; }/** * Check the user object annotations in Group A and group B for the checksum * PS: is a group within the check plus the B-group check, not the checksum at the same time in two groups! */@PostMapping ("/validationtest3") public String validationTest3 (@RequestBody user user) {string valid = Val Idatorutils.validentity (user, A.class, b.class); if (null! = valid) return valid; Do somethings return "verification pass"; }/** * Check in Parameter object specified field * Where grouping can not be passed, if so, please note that the field must be under this group, otherwise it will not be checked */@PostMapping ("/validationtest4") public Strin G ValidationTest4 (@RequestBody user user) {String valid = Validatorutils.validproperty (user, "age", B.class); if (null! = valid) return valid; Do somethings return "verification pass"; }/** * Verify the TEST4 on the top of the page */@PostMapping ("/VALIDATIONTEST5") public String validationTest5 (@RequestBody User User) {String valid = Validatorutils.validproperty (user, "age", A.class); if (null! = valid) return valid; Do somethings return "verification pass"; }/** * Use Method 7 to draw the tool class */@PostMapping ("/validationtest8") public String validationTest8 (@RequestBody @Valid User user, bindingresult result) {String errormsg = validatorutils.validentity (re Sult); if (Stringutils.isnotblank (errormsg)) return errormsg; Do somethings return "verification pass"; }
(3) Supplement: User class
public class User { @NotBlank(message = "用户名不能为空串",groups = A.class) private String username; @NotNull(message = "年龄不能为空",groups = B.class) private String age; @NotBlank(message = "身高不能为空", groups = {A.class, B.class}) private String height; @NotEmpty(message = "孩子列表不能为空") private List<Object> childs; @Email(message = "email不正确") private String email; //省略get set 方法}
Extended section
Empty check
@Null
: Verify that a parameter must be empty PS: no =. =, the rest of the empty checks are already spoken on the top
Length Check
@Size(min=, max=)
: Verifies whether the length of the object (array,collection,map,string) is within a given range
@Length(min=, max=)
: is the length within range
Booelan Check
@AssertTrue
: Verifies whether a Boolean object is True
@AssertFalse
: Verifies whether the Boolean object is False
Numeric check : Recommended on the base type wrapper type and on the string type
@Min
: Verify Minimum value
@Max
: Verify Maximum Value
@DecimalMax
: decimal value cannot be greater than set value, decimal exists precision
@DecimalMin
: decimal value cannot be less than set value, decimal exists precision
@Digits
: Verifies that numbers and string composition are legitimate
Scope check
@Range(min=, max=)
: Verifies the minimum and maximum range of objects
Number check
@CreditCardNumber
: Credit card verification (implementation of Hibernate)
@Email
: Verify that the e-mail address, if NULL, is not validated and validated (both validation and Hibernate are implemented)
Date Check
@Past
: Verifies whether the date and Calendar objects are before the current time, and Null is considered to be validated
@Future
: Verifies whether the date and Calendar objects are after the current time, and Null is considered to be validated
Regular-expression checks
@Pattern(regexp = "")
: Validates a string with a regular expression, accepts a sequence of characters, RegExp is required, and is considered to be validated when NULL is modified
End
It's been a night. The actual usage of the verification, referring to some of the blog post, the most of the content of the reference stuck below, basically official documents and a foreign language website
Docs.oracle.com/javaee/7/api/toc.htm
docs.jboss.org/hibernate/stable/validator/api/
Www.baeldung.com/javax-validation
42618593
This article is code: Github.com/hellxz/myutils.git
Disclaimer: The contents of this article are not permitted, but please specify the source