JSR-303 Bean Validation Introduction and Spring MVC server-side validation best practices

Source: Internet
Author: User

At any time, when it comes to dealing with the business logic of an application, data validation is something you have to consider and face.

The application must have some means to ensure that the input parameters are correct in context.

Layered applications In many cases, the same data validation logic will appear on different tiers, which can lead to code redundancy and some management issues.

To avoid this or that situation, it is best to bind the validation logic to the corresponding data model.

1. JSR-303 Bean Validation

The JSR is the abbreviation for Java specification requests and is a formal request to the JCP (Java Community Process) to propose a new standardized technical specification.

Anyone can submit a JSR to add new APIs and services to the Java platform, and the approved specification covers all areas of Java and is interesting to know.

Bean Validation is a runtime data validation framework that defines the appropriate metadata model and API for JavaBean validation.

The default metadata is Java Annotations, and of course XML can be used to overwrite and extend existing metadata information.

In your application, you can ensure the correctness of the data model by using Bean Validation or your own defined constraint, such as @NotNull, @Max, @ZipCode.

Constraint can be annotated to fields, getter methods, classes, or interfaces above. For some specific needs, users can easily develop customized constraint.

Hibernate Validator as a reference implementation for Bean Validation. Provides the implementation of all the built-in constraint in the JSR 303 specification, in addition to some additional constraint.

Specifications defined in Sun Validation-api.jar constraint

Hiber-validator customization of several constraint

2. Spring MVC Service-side validation practice

With just a simple three-step process, you can test the data model in Spring MVC, first by relying on the jar you need.

      <Dependency>            <groupId>Org.hibernate</groupId>            <Artifactid>Hibernate-validator</Artifactid>            <version>6.0.1.Final</version>        </Dependency>

Then add the validation annotations on the need to validate the data model, and if the data model is to introduce other companies or projects, it is also possible to write XML.

 Public classUservo {@NotNull (message= "UUID cannot be empty!" ")    PrivateString uuid; @NotEmpty (Message= "User name cannot be empty!" ")    PrivateString name; PrivateString passwd; PrivateString sex; PrivateDate birthday; @Length (min= one, max = one, message = "The phone number must be 11 bits long!" ")    PrivateString Phone; PrivateString photo; @Email (Message= "e-mail address is not legal!" ")    PrivateString Email; PrivateString yxbz; PrivateString sorts; ... setter/Getter}

And finally, the process of validating and getting results, you can write a generic method of hard coding to use in your project, like so.

   Private void Validbean (Object targerbean) {        = validation.builddefaultvalidatorfactory ();         = factory.getvalidator ();        Set<ConstraintViolation<Object>> violations = validator.validate (targerbean);          for (constraintviolation<object> violation:violations) {            System.out.println (violation.getmessage ());        }    }

Or you can use Spring MVC encapsulated Validated annotations and Bindingresult objects to do a more elegant job of verifying things.

Isn't it easy to be a tart? This article is only for the purpose of the specific project specific scenarios please self-pinch.

JSR-303 Bean Validation Introduction and Spring MVC server-side validation best practices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.