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 perform data check Java Bean Validation 2.0

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Today, I would like to talk to you about how to carry out data verification Java Bean Validation 2.0. maybe many people don't know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something from this article.

We know that programs must be layered in general, and different layers are generally developed by different people. If you are an experienced programmer, I am sure you have seen the same check code in different layers, which is some sense of junk code. To solve this problem, Bean Validation defines the corresponding metadata model and API for JavaBean validation. The default metadata is all kinds of Java Annotations, of course, it also supports xml mode, and you can also extend Bean Validation. It can be said that Bean Validation is an extension of JavaBean, which can be laid out in any layer of code, not limited to Web applications or end applications.

Java Bean Validation

JSR is an acronym for Java Specification Requests, which means Java specification proposal. With regard to data verification, the latest is JSR380, which is JSR Standard 380. Bean Validation is a framework for validating parameters by configuring annotations. It consists of two parts, Bean Validation API (specification) and Hibernate Validator (implementation).

Simple Demo example

The minimum version requirement for Java is Java 8

Container verification is supported, and container content is constrained by annotations of TYPE_USE type: `List`

Support date / time check, @ Past and @ Future

Expand metadata (add comments): @ Email,@NotEmpty,@NotBlank,@Positive, @ PositiveOrZero,@Negative,@NegativeOrZero,@PastOrPresent and @ FutureOrPresent

For example, @ Email, @ NotEmpty and @ NotBlank were provided by Hibernate before. Hibernate automatically abdicated and marked as expired after the 2.0 standard.

The only implementation of Bean Validation 2.0 is Hibernate Validator. (there's actually Apache BVal, but you know, forget it)

For Hibernate Validator, it also extends some annotation support.

Therefore, there is nothing to choose from for the implementation of Java Bean Validation, so import Hibernate Validator (the latest version):

POM joining

Org.projectlombok lombok 1.16.20 org.hibernate hibernate-validator 6.0.17.Final org.apache.tomcat.embed tomcat-embed-el 8.5.29

Write a Java Bean

@ Getter@Setter@ToStringpublic class Person {/ / error message message is customizable @ NotNull (message = "name cannot be null") public String name; @ Positive public Integer age; @ NotEmpty private List emails; @ Future private Date start;} public static void main (String [] args) {Person person = new Person (); / / person.setName ("fsx"); person.setAge (- 1) / / email check: although it is List, you can check person.setEmails (Arrays.asList ("fsx@gmail.com", "baidu@baidu.com", "aaa.com")); / / person.setStart (new Date ()); / / start needs to be a future time: Sun Jul 21 10:45:03 CST 2019 / / person.setStart (new Date (System.currentTimeMillis () + 10000)) / / Verification passes / / A pair of person verifies and gets the result (obviously the default verifier when used) retains the message Set result = Validation.buildDefaultValidatorFactory () .getValidator () .validate (person) / / A pair of results are traversed to output result.stream (). Map (v-> v.getPropertyPath () + "+ v.getMessage () +": "+ v.getInvalidValue ()) .forEach (System.out::println) / / use hibernateValidator HibernateValidatorConfiguration configuration = Validation.byProvider (HibernateValidator.class) .configure () .failFast (false); ValidatorFactory validatorFactory = configuration.buildValidatorFactory (); Set sets= validatorFactory.getValidator () .validate (person) Sets.stream () .map (v-> v.getPropertyPath () + "+ v.getMessage () +": "+ v.getInvalidValue ()) .forEach (System.out::println);}

Run the mian function and print the output from the console

Name name cannot be null: null / / where the error message is your own custom content age must be a positive number:-1emails [2]. Is not a legitimate email address: aaa.com

Common validation rules are as follows:

@ AssertFalse verify that the boolean type can only be false@AssertTrue that the boolean type can only be true

For details of some other rules, see:

Core API Analysis Validation Class under javax.validation.constraints package

The official definition is: This class is the entry point for Bean Validation. As the entrance to the verification, there are three ways to start it. Here we mainly look at the most common startup methods:

The simplest way: use the default ValidatorFactory factory = Validation.buildDefaultValidatorFactory ()

A type-safe ValidationProvider implementation can be provided directly. For example, HibernateValidator is an implementation of ValidationProvider:

HibernateValidatorConfiguration configuration = Validation.byProvider (HibernateValidator.class) / / .providerResolver (...) / / since Provider is specified, this parameter can be selected as .configure () .failFast (false); ValidatorFactory validatorFactory = configuration.buildValidatorFactory ()

After reading the above, do you have any further understanding of how to perform data validation Java Bean Validation 2.0? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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

Internet Technology

Wechat

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

12
Report