Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java SpringBoot Validation

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to use Java SpringBoot Validation", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use Java SpringBoot Validation" this article.

Mention the basic validation of input parameters (non-null, length, size, format … ), in the past, we still use handwritten code, all kinds of if, else, StringUtils.isEmpty, CollectionUtils.isEmpty... Oh, I feel like I'm going crazy, it's too cumbersome, Low is exploding. In fact, Java Ecology provides a set of standard JSR-380 (aka. Bean Validation 2.0 part of Jakarta EE and JavaSE), which has become the de facto standard for object validation, which can be done in the form of annotations (such as @ NotNull, @ Size... To validate the properties of the bean Hibernate Validator implements this set of standards, and SpringBoot Validation seamlessly integrates the functions of Hibernate Validator, custom verifier and automatic verification. The SpringBoot integration Validation is expanded below.

Constraints classification

The constrants comments supported by JSR-380 are summarized in the following table:

Classification annotation applicable object null verifies that non-empty @ NotNull all objects No is not null non-empty @ NotEmptyCharSequence, Collection, Map, ArrayNo is not null, not "", size > 0 non-empty @ NotBlankCharSequenceNo is not null, length after trim is greater than 0 non-empty @ Null all objects Yes is null length @ Size (min=0, max=Integer.MAX_VALUE) CharSequence, Collection, Map, ArrayYes string length, collection size size @ PositiveBigDecimal, BigInteger, byte, short, int, long, float, doubleYes number > 0 size @ PositiveOrZeroBigDecimal, BigInteger Byte, short, int, long, float, doubleYes numbers > = 0 size @ NegativeBigDecimal, BigInteger, byte, short, int, long, float, doubleYes digits constraintViolations.stream () .flatMap (constraintViolation-> {String path = constraintViolation.getPropertyPath (). ToString () Path = path.substring (path.lastIndexOf (DOT) + 1); String errMsg = constraintViolation.getMessage (); return Stream.of (path, SEPARATOR_COLON, errMsg, SEPARATOR_COMMA) Collectors.joining () .map (msg-> msg.substring (0, msg.length ()-SEPARATOR_COMMA.length () .orElse (null);}}

Parameter verification failed the returned result example:

Note: CommonResult returns the result uniformly and can be adjusted according to your own business.

Custom constraints

Custom field constraint annotations are mainly divided into the following steps:

(1) define constraint annotation annotations and their attributes

(2) through the concrete validator associated with the meta-annotation @ Constraint (validatedBy = {})

(3) implement validator logic

@ DateFormat

An example of a specific string date format constraint @ DateFormat definition is as follows:

Import javax.validation.Constraint;import javax.validation.Payload;import java.lang.annotation.*;import static java.lang.annotation.ElementType.ANNOTATION_TYPE;/** * The annotated {@ code CharSequence} must match date format. * The default date format is "yyyy-MM-dd". * Can override with property "format". * see {@ link java.time.format.DateTimeFormatter}. *

* Accepts {@ code CharSequence}. {@ code null} elements are considered valid. * * @ author luo * @ date 2021-09-05 * / @ Documented@Constraint (validatedBy = DateFormatValidator.class) @ Target ({ElementType.METHOD, ElementType.FIELD, ANNOTATION_TYPE,}) @ Retention (RetentionPolicy.RUNTIME) public @ interface DateFormat {String message () default "date format is incorrect"; String format () default "yyyy-MM-dd"; Class [] groups () default {}; Class [] groups () default {}; Class

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report