avatarlance

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2915

Abstract

;</span></pre></div><p id="1a5d">The following are the @valid-related annotations. Adding different annotations to the attributes of the entity class can realize the verification function.</p><ul><li>@Null restrict property can only be null.</li><li>@NotNull restrict property is not nullable.</li><li>@Max(value) restrict property must be a number not greater than the specified value.</li><li>@Min(value) restrict property must be a number not less than the specified value.</li><li>@Digits(integer, fraction) restrict property must be a decimal, and the number of digits in the integer part cannot exceed <i>integer</i>, and the number of digits in the decimal part cannot exceed <i>fraction.</i></li><li>@Past restrict property must be a past date.</li><li>@Future restrict property must be a future date.</li><li>@Pattern(value) restrict property must conform to the specified regular expression.</li><li>@Size(max, min) limit character length must be between min and Max.</li><li>@NotEmpty valid property value is not nullable, the string length is not 0, and the collection size is not 0.</li><li>@NotBlank valid property value is not null, and after trim() the length is not 0.</li><li>@Email Verify that the attribute value is a string in email format.</li></ul><p id="7983">Using the @valid annotation to complete parameter verification is very simple. You only need to add <a href="https://javarevisited.blogspot.com/2017/04/difference-between-autowired-and-inject-annotation-in-spring-framework.html">appropriate annotations</a> to the attributes of the entity class. The same example of new user registration is above.</p> <figure id="b353"> <div> <div>

            <iframe class="gist-iframe" src="/gist/lance12138/f8963053971e2ab8e9ea64ce1c0306a4.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="f850">See, it’s that simple. A few annotations complete the complex verification logic. When the verification of the target parameter fails, the system will throw an <code>MethodArgumentNotValidException</code> exception. Then, we can use <code>@ExceptionHandler</code>handle the verification results.</p><h2 id="bddc">Use @Exceptionhandler to Uniformly Handle Validation Results</h2>
    <figure id="7781">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/lance12138/aff290b10595485f4484ee230890c242.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="f742">A global exception handler class is created here. We use the <i>parameterExceptionHandler</i> method to catch <code>MethodArgumentNotValidException</code> exceptions, and finally, unif

Options

ormly handle the results of validation failures. This method will get the error message after the validation of each field fails. Here, I use the <code>ErrorResult</code> class to return the error message. When we start the service, we use postman to initiate a post request( <a href="http://localhost:8080/user/register">http://localhost:8080/user/register</a> ), we do not enter any parameters and return the result:</p><div id="d9fd"><pre>{
"<span class="hljs-selector-tag">code</span>": -<span class="hljs-number">1</span>,
<span class="hljs-string">"msg"</span>: <span class="hljs-string">"the user phone is illegal."</span>
}</pre></div><p id="5c5e">This article briefly introduces the use of @valid to validate API requests in spring boot. I hope this article can help you. Thank you for reading.</p><div id="9680" class="link-block"> <a href="https://readmedium.com/four-tricks-to-eliminate-complex-conditional-expressions-4452b319feea"> <div> <div> <h2>Four Tricks to Eliminate Complex Conditional Expressions</h2> <div><h3>Have you had enough of if-else complex nesting? I may give you some suggestions to improve the extensibility of the…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*ieXaavHBhInXJiKyK4RTEA.jpeg)"></div> </div> </div> </a> </div><div id="4e79" class="link-block"> <a href="https://readmedium.com/ten-optimization-tricks-to-make-your-java-application-run-faster-9742f568ed6f"> <div> <div> <h2>Ten Optimization Tricks to Make Your Java Application Run Faster</h2> <div><h3>These tricks may improve the performance of your application several times.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*xJknqmZzptRvuQRZp_nFCg.jpeg)"></div> </div> </div> </a> </div><div id="9602" class="link-block"> <a href="https://readmedium.com/2-must-know-tricks-of-unit-testing-with-spring-boot-21c85987e47"> <div> <div> <h2>2 Must-Know Tricks of Unit Testing with Spring Boot</h2> <div><h3>To improve the quality of unit testing of spring projects, you need to know about these tricks</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*RK5S3BIODpLmc5Lg4kY3LQ.jpeg)"></div> </div> </div> </a> </div></article></body>

Spring Boot Application Use @valid to Validate API Request

Using @valid can make your Request validation easier.

When we develop the rest API, we believe that everyone needs to verify the legitimacy of the input parameters of the interface. Some beginners may use many if-else conditional expressions for verification. Take a new user registration as an example:

Such code can achieve the purpose of parameter verification, but careful readers may have found that if we want to write many interfaces like this, we need to write a lot of verification code repeatedly, which is obviously not elegant. We can use the @valid annotation to help us simplify the validation logic.

Using @Valid

The hibernate-validator implements @Valid. spring-boot-start-web already contains this library, so there is no need to introduce dependencies. If it is a non-spring project, two Maven dependencies need to be used.

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
 
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.14.Final</version>
</dependency>

The following are the @valid-related annotations. Adding different annotations to the attributes of the entity class can realize the verification function.

  • @Null restrict property can only be null.
  • @NotNull restrict property is not nullable.
  • @Max(value) restrict property must be a number not greater than the specified value.
  • @Min(value) restrict property must be a number not less than the specified value.
  • @Digits(integer, fraction) restrict property must be a decimal, and the number of digits in the integer part cannot exceed integer, and the number of digits in the decimal part cannot exceed fraction.
  • @Past restrict property must be a past date.
  • @Future restrict property must be a future date.
  • @Pattern(value) restrict property must conform to the specified regular expression.
  • @Size(max, min) limit character length must be between min and Max.
  • @NotEmpty valid property value is not nullable, the string length is not 0, and the collection size is not 0.
  • @NotBlank valid property value is not null, and after trim() the length is not 0.
  • @Email Verify that the attribute value is a string in email format.

Using the @valid annotation to complete parameter verification is very simple. You only need to add appropriate annotations to the attributes of the entity class. The same example of new user registration is above.

See, it’s that simple. A few annotations complete the complex verification logic. When the verification of the target parameter fails, the system will throw an MethodArgumentNotValidException exception. Then, we can use @ExceptionHandlerhandle the verification results.

Use @Exceptionhandler to Uniformly Handle Validation Results

A global exception handler class is created here. We use the parameterExceptionHandler method to catch MethodArgumentNotValidException exceptions, and finally, uniformly handle the results of validation failures. This method will get the error message after the validation of each field fails. Here, I use the ErrorResult class to return the error message. When we start the service, we use postman to initiate a post request( http://localhost:8080/user/register ), we do not enter any parameters and return the result:

{  
    "code": -1,  
    "msg": "the user phone is illegal."  
}

This article briefly introduces the use of @valid to validate API requests in spring boot. I hope this article can help you. Thank you for reading.

Spring Boot
Validation
Java
Programming
Software Development
Recommended from ReadMedium