spring validation Multilayer Object Verification Tutorial

  • 2021-11-29 23:50:49
  • OfStack

Directory spring validation Multilayer Object Verification 1, Layer 1 Object Definition 2, Layer 2 Object 3, Controller Layer Verification Using Message Content Returned from Multiple Fields of validation Verification Object Sequence Random Problem Problem Description Solution

spring validation Multilayer Object Verification

1. Layer 1 object definition


import java.io.Serializable; 
import javax.validation.Valid;
/**   
 *  Request parameter 
 * @Title: ReqIn.java 
 * @Package com.spring.pro.model 
 * @Description:  
 * @author ybwei  
 * @date 2018 Year 9 Month 18 Day   Afternoon 1:43:26 
 * @version V1.0   
 */
public class ReqIn<T> implements Serializable{ 
 private static final long serialVersionUID = 25549320423002325L;
 /**
  *  Request header information 
  */
 private String head;
 /**
  *  Request subject information 
  */
 @Valid
 private T data;
 public String getHead() {
  return head;
 }
 public void setHead(String head) {
  this.head = head;
 }
 public T getData() {
  return data;
 }
 public void setData(T data) {
  this.data = data;
 }
}

2. Layer 2 objects


import java.io.Serializable; 
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**   
 * @Title: User.java 
 * @Package com.spring.pro.model 
 * @Description:  
 * @author ybwei  
 * @date 2018 Year 9 Month 18 Day   Afternoon 1:46:15 
 * @version V1.0   
 */
public class User implements Serializable{ 
 private static final long serialVersionUID = 6747944028911495569L;
 private String id;
 @NotBlank
 private String name;
 @NotNull
 private Integer age;
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
}

3. Use of Controller layer verification


import javax.validation.Valid; 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController; 
import com.alibaba.fastjson.JSON;
import com.spring.pro.model.ReqIn;
import com.spring.pro.model.User;
/**   
 * @Title: UserController.java 
 * @Package com.spring.pro.controller 
 * @Description:  
 * @author ybwei  
 * @date 2018 Year 9 Month 18 Day   Afternoon 1:48:14 
 * @version V1.0   
 */
@RestController
public class UserController {
 private Logger logger=LoggerFactory.getLogger(getClass());
 
 /**
  *  Calibration 
  * @param reqIn
  * @return
  * @author ybwei
  */
 @PostMapping("/valid")
 public HttpStatus valid(@Valid @RequestBody ReqIn<User> reqIn){
  logger.info("reqIn:{}",JSON.toJSONString(reqIn));
  return HttpStatus.OK;
 }
}

validation Verification Object Multiple Fields Return Message Content Order Random Problem

Problem description

The code in model is as follows


public class User {
  @NotNull(message = "id Cannot be empty ", groups = UserGroup.UPDATE.class)
  protected Integer id;
  /**
   *  Name 
   */
  @NotBlank(message = " Please enter a name ", groups = UserGroup.ADD.class)
  private String name;
  /**
   *  Gender 
   */
  @NotBlank(message = " Please enter gender ", groups = UserGroup.ADD.class)
  private String sex;
  /**
   *  Mobile phone number 
   */
  @NotBlank(message = " Please enter your mobile phone number ", groups = UserGroup.ADD.class)
  private String phone;
  /**
   *  Mailbox 
   */
  @NotBlank(message = " Please enter the mailbox ", groups = UserGroup.ADD.class)
  private String email;
  /**
   *  Company name 
   */
  @NotBlank(message = " Please enter a company name ", groups = UserGroup.ADD.class)
  private String companyName;
  /**
   *  Position 
   */
  @NotBlank(message = " Please enter a job ", groups = UserGroup.ADD.class)
  private String position;
}

The defined packet interface is as follows


public interface UserGroup {
  interface ADD {
  }
  interface UPDATE {
  }
}

When using the @ Validated annotation of Spring to validate multiple parameters in an object, The data in the bindingResult. getAllErrors () exception message set in MethodArgumentNotValidException is returned in a random order if it is found at the MethodArgumentNotValidException exception interceptor that there are multiple non-conforming and validation rule parameters. In normal logic, we definitely want to return the first non-conforming field error message to the user in sequence.

Solution

After 1 search, you can specify a different group for each validated annotation on the class, and then add @ GroupSequence to create 1 interface interface to summarize those interfaces added to the field, as follows:


public interface UserGroup {
  @GroupSequence({ADD.NAME.class,
                  ADD.SEX.class,
                  ADD.PHONE.class,
                  ADD.EMAIL.class,
                  ADD.COMPANY_NAME.class,
                  ADD.POSITION.class})
  interface ADD {
    interface NAME {}
    interface SEX {}
    interface PHONE {}
    interface EMAIL {}
    interface COMPANY_NAME {}
    interface POSITION {}
  }
  interface UPDATE {
  }
}

Model


@NoArgsConstructor
public class User {
  @NotNull(message = "id Cannot be empty ", groups = UserGroup.UPDATE.class)
  protected Integer id;
  /**
   *  Name 
   */
  @NotBlank(message = " Please enter a name ", groups = UserGroup.ADD.NAME.class)
  private String name;
  /**
   *  Gender  1. Male  2. Female  3. Unknown 
   */
  @NotBlank(message = " Please enter gender ", groups = UserGroup.ADD.SEX.class)
  private String sex;
  /**
   *  Mobile phone number 
   */
  @NotBlank(message = " Please enter your mobile phone number ", groups = UserGroup.ADD.PHONE.class)
  private String phone;
  /**
   *  Mailbox 
   */
  @NotBlank(message = " Please enter the mailbox ", groups = UserGroup.ADD.EMAIL.class)
  private String email;
  /**
   *  Company name 
   */
  @NotBlank(message = " Please enter a company name ", groups = UserGroup.ADD.COMPANY_NAME.class)
  private String companyName;
  /**
   *  Position 
   */
  @NotBlank(message = " Please enter a job ", groups = UserGroup.ADD.POSITION.class)
  private String position;
}

Specify the order of the set interface array in the @ GroupSequence annotation, and then directly put the interface class UserGroup. ADD. class in the @ Validated annotation to public Result add (@ Validated (UserGroup. ADD. class) @ RequestBody User user), validation will return error messages in sequence, and the first error message in the exception interceptor will be MethodArgumentNotValidException. getBindingResult (). getAllErrors (). get (0). getDefaultMessage ()


Related articles: