Spring Boot for Bean Validate and method Validate

Source: Internet
Author: User
Tags ranges

Springboot has implemented the JSR-349 authentication specification interface internally through the integrated hibernate-validation, as long as the direct use of the Springboot project is done.

Typically used in a controller to verify the parameters coming from the front end.

Authentication is divided into two types: validating encapsulated beans or validating method simple parameters

First, carry out beanvalidate

1. Defining beans

public class Validbean {    @NotNull (message = "Name cannot be empty")    private String name;    @Min (value =, message = "must be greater than")    private int age;    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    public int getage () {        return age;    }    public void Setage (int.) {        this.age = age;    }}

2. Use

@RequestMapping ("Bean")    @ResponseBody public    String Say (@Valid validbean Bean, Bindingresult bindingresult) {                return bindingresult.haserrors ()? Bindingresult.getfielderror (). Getdefaultmessage (): "Incorrect";    }

3. Note
@Valid and Bindingresult is one by one corresponding, if there are multiple @valid, then each @valid followed by Bindingresult is the verification results of this @valid, the order can not be chaotic

4.Api
@Null can only be null
@NotNull cannot be null note invalid on base type, base type has default initial value
The @AssertFalse must be false
@AssertTrue must be True

string/array/collection check: (The string itself is a group of numbers)
@Pattern (regexp= "Reg") to verify that the string satisfies the regular
@Size (max, min) to validate strings, arrays, collection length ranges
@NotEmpty Verify that the string is not empty or null
@NotBlank Verify that the string is not null or is not empty after trim ()

Numeric check: A string that verifies whether a string is a number that satisfies a limit
@Max rules worth the upper limit int
@Min regulations worth the lower limit
@DecimalMax ("10.8") constructs a bigdecimal with the incoming string, with a value less than this value
@DecimalMin can be used to limit the size of floating-point numbers
@Digits (Int1, Int2) limits a decimal, integer precision is less than int1, fractional precision is less than int2
@Digits no arguments to verify that the string is legitimate
@Range (min=long1,max=long2) to check whether the numbers are between ranges
These all include boundary values

Date Check: Date/calendar
@Post limit a date that must be a date in the past
@Future limit a date, the date must be a future date

Additional validation:
@Vaild recursive validation, used for objects, arrays, and collections, to perform one by one checks on elements of an object, elements of an array
@Email is used to verify whether a string is a valid right-key address, an empty string, or a null-count validation Pass
@URL (protocol=,host=,port=,regexp=,flags=) is used to verify whether a string is a legitimate URL

Second, carry out methodvalidate

1. Inject Methodvalidationpostprocessor beans

@Bean public    methodvalidationpostprocessor methodvalidationpostprocessor () {        return new Methodvalidationpostprocessor ();    }

2. Add annotations to the classes you want to methodvalidate @validated
3. Use in methods

@Controller @validated@requestmapping ("valid") public class Validcontroller {@RequestMapping ("/check") @ Responsebodypublic String Check (@Min (value = 2,message = "Age must be greater than 2") int age) {return ' "+ Age;}}

4. Handling Validation Failures
The default checksum will cause the method to throw unchecked Exception, which in Springboot will jump to the error page by default, so just add a handler for this exception:

@ExceptionHandler (value = {Constraintviolationexception.class})    @ResponseBody public    String Handleresourcenotfoundexception (constraintviolationexception e) {        set<constraintviolation<?>> violations = E.getconstraintviolations ();        StringBuilder Strbuilder = new StringBuilder ();        for (constraintviolation<?> violation:violations) {            strbuilder.append (violation.getmessage () + "\ n");        }        return strbuilder.tostring ();    }

5. Note
If @validated is used, then beanvalidate throws an exception instead of the previous package in Bindingresult

Third, custom exception handling
Use to re-check, online a lot of examples

Four

Validation is based on spring AOP, so any spring bean can actually use these annotations for validation, such as the service layer. But the most used is the controller layer.

Spring Boot for Bean Validate and method Validate

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.