Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use @ Validated packet check in Spring

Shulou Source: shulou.com Published: 2022-06-03 03:17:18 09月13日 Update

This article mainly introduces "how to use @ Validated grouping check in Spring". In daily operation, I believe many people have doubts about how to use @ Validated grouping check in Spring. The editor consulted all kinds of data and sorted out simple and useful operation methods. I hope it will be helpful to answer the doubts about "how to use @ Validated grouping check in Spring". Next, please follow the editor to study!

Catalogue

The use of Spring @ Validated packet check

Introduce POM dependency

Define the Vo that receives the data

Unified exception handling class

Test class

Page effect test

Use @ Validated to group pits encountered

Solution.

The use of Spring @ Validated packet check

Through this article you can learn the basic use of @ Validated and how to handle data exceptions uniformly in spring-boot.

The Spring Validation verification framework provides @ Validated (Spring's JSR-303 specification, a variation of standard JSR-303) for parameter verification, and javax provides @ Valid (standard JSR-303 specification). With BindingResult, you can directly provide parameter verification results.

When verifying that the input parameter conforms to the specification, there is not much difference in basic validation functionality using @ Validated or @ Valid. However, the two functions are different in grouping, annotations, nested validation, and so on. Generally speaking, @ validated is equivalent to an upgraded version of @ Valid validation, which is more powerful.

Next, let's take a direct look at how to use

Introduce POM dependency org.hibernate hibernate-validator 5.2.4.Final

Define the public grouping class (for marking grouping, which can be defined in Vo as later, but it is recommended that some commonly used definitions be external), as follows

Public interface Add {} public interface Edit {}

Define the Vo that receives the data

Note the use of grouping in the annotations. For demonstration, a special grouping class is defined internally.

Import com.example.jsr.commmon.Add;import com.example.jsr.commmon.Edit;import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.Pattern Public class ParamsVo {/ / specially used to modify age markers use flexible placement position public interface ModifyAge {} / / valid public static final String AGE_REG = "/ ^ (?: [1-9] [0-9]? | 1 [01] [0-9] | 120) $/" @ NotBlank (groups = {Edit.class, ParamsVo.ModifyAge.class}, message = "failed, id cannot be empty") private String id; @ NotBlank (groups = {Edit.class, Add.class}, message = "failed, name cannot be empty") private String name / / customize a regular @ NotBlank (groups = {Add.class, ParamsVo.ModifyAge.class}, message = "failed, please fill in age") @ Pattern (regexp = AGE_REG,groups = {Add.class, ParamsVo.ModifyAge.class}, message = "failed, please fill in the correct age") private String age;. Omit the setter getter method.} uniform exception handling class import org.springframework.validation.BindException;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody / * * Global exception handling * / @ ControllerAdvicepublic class GlobalExceptionHandler {@ ExceptionHandler (BindException.class) @ ResponseBody public String handlerUnexpectedTypeException (BindException ex) {BindingResult result = ex.getBindingResult (); if (result.hasErrors ()) {FieldError fieldError = result.getFieldError (); if (fieldError! = null) {return fieldError.getDefaultMessage () }} return "failed, please refresh and try again";} @ ExceptionHandler (Exception.class) @ ResponseBody public String handlerException (Exception ex) {ex.printStackTrace (); return "failed, please refresh and try again";}} Test class import com.example.jsr.Vo.ParamsVo;import com.example.jsr.commmon.Add;import com.example.jsr.commmon.Edit;import org.springframework.stereotype.Controller Import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; @ Controller@RequestMapping ("/ validated/test") public class ValidatedTestController {@ RequestMapping ("/ add") @ ResponseBody public String add (@ Validated (Add.class) ParamsVo paramsVo) {System.out.println (String.format ("add obj = {% s}", paramsVo.toString (); return "success" } @ RequestMapping ("/ edit") @ ResponseBody public String editAll (@ Validated ({Edit.class,ParamsVo.ModifyAge.class}) ParamsVo paramsVo) {System.out.println (String.format ("edit obj = {% s}", paramsVo.toString (); return "success";}} Page effect Test

Do not enter age

Fill in an error age

So far, I believe there is no problem with the basic use.

Use @ Validated to group pits encountered

When using @ Validate annotation grouping check, if you specify a grouping, all attributes that need to be validated must add the specified grouping to be validated

Solution.

It is not indicated that the attributes of the packet belong to Default, so the packet interface inherits Default can solve the problem.

At this point, the study on "how to use @ Validated packet check in Spring" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Grouping validation learning processing testing functions data annotations unification special next methods parameters attributes age effects methods more standards tags Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MySQL Docker Linux Huawei