In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to achieve spring validation multi-layer object check". In daily operation, I believe that many people have doubts about how to achieve spring validation multi-layer object check. The editor has consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to achieve spring validation multi-layer object check". Next, please follow the editor to study!
Catalogue
Spring validation multi-layer object check
1. Layer 1 object definition
2. The second layer object
3. Use of Controller layer verification
Random order of message content returned by multiple fields of validation verification object
Problem description
Solution.
Spring validation Multi-layer object Verification 1. Layer 1 object definition import java.io.Serializable; import javax.validation.Valid;/** * request parameters * @ Title: ReqIn.java * @ Package com.spring.pro.model * @ Description: * @ author ybwei * @ date on September 18, 2018 1:43:26 * @ version V1.0 * / public class ReqIn implements Serializable {private static final long serialVersionUID = 25549320423002325L / * * request header information * / private String head; / * request body 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 object 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 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, Controller layer verification using 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 1:48:14 * @ version V1.0 * / @ RestControllerpublic class UserController {private Logger logger=LoggerFactory.getLogger (getClass ()) / * param reqIn * @ return * @ author ybwei * / @ PostMapping ("/ valid") public HttpStatus valid (@ Valid @ RequestBody ReqIn reqIn) {logger.info ("reqIn: {}", JSON.toJSONString (reqIn)); return HttpStatus.OK;}} description of the random order of messages returned by multiple fields of the validation verification object
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 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; / * email * / @ NotBlank (message = "Please enter email", groups = UserGroup.ADD.class) private String email; / * Company name * / @ NotBlank (message = "Please enter your company name", groups = UserGroup.ADD.class) private String companyName / * Job * / @ NotBlank (message = "Please enter a job", groups = UserGroup.ADD.class) private String position;}
The packet interfaces defined are as follows
Public interface UserGroup {interface ADD {} interface UPDATE {}}
When verifying multiple parameters in the object using the @ Validated annotation of Spring, it is found at the MethodArgumentNotValidException exception interceptor that if there are multiple parameters that do not match the conditions and the verification rules, the data in the bindingResult.getAllErrors () exception message set in MethodArgumentNotValidException is returned in random order. According to normal logic, we definitely want to return the first non-conforming field error message to the user in order.
Solution.
After some search, it is found that each validated annotation on the class can be assigned a different group, and then add @ GroupSequence to summarize the interfaces added to the field when creating an interface interface, 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
@ NoArgsConstructorpublic class User {@ NotNull (message = "id cannot be empty", groups = UserGroup.UPDATE.class) protected Integer id; / * * name * / @ NotBlank (message = "Please enter 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 number * / @ NotBlank (message = "Please enter Mobile number", groups = UserGroup.ADD.PHONE.class) private String phone; / * * mailbox * / @ NotBlank (message = "Please enter email", groups = UserGroup.ADD.EMAIL.class) private String email / * * Company name * / @ NotBlank (message = "Please enter the company name", groups = UserGroup.ADD.COMPANY_NAME.class) private String companyName; / * Job * / @ NotBlank (message = "Please enter the title", groups = UserGroup.ADD.POSITION.class) private String position;}
Specify the order of the interface array set 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 order, and you can MethodArgumentNotValidException.getBindingResult (). GetAllErrors (). Get (0). GetDefaultMessage (0) in the exception interceptor
At this point, the study on "how to implement spring validation multi-layer object verification" 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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.