In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "parameter verification method in Java". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the parameter verification method in Java".
1. Parameter verification in Java (non-Spring version) 1.1. Preface
Why do I always encounter this abnormal problem? we know that most of the time, our parameter verification is carried out on the incoming parameters of the controller layer. Our common verification method is to introduce the following jar package, add @ Validated to the parameters, and annotate the parameters of the Bean object differently. You should be familiar with the common practice of Spring.
But the demand I encounter now, because boss pursues versatility, we have only one entry for controller, which distinguishes which service to call by passing in different tradeCode in the parameters. Then I have to verify the parameters on each service method. After my test, adding the annotation no longer works.
Javax.validation validation-api 1.1.0.Final @ PostMapping ("/ save/valid") public RspDTO save (@ RequestBody @ Validated UserDTO userDTO) {userService.save (userDTO); return RspDTO.success ();} @ Datapublic class UserDTO implements Serializable {private static final long serialVersionUID = 1L; / * * user ID*/ @ NotNull (message = "user id cannot be empty") private Long userId / * * user name * / @ NotBlank (message = "user name cannot be empty") @ Length (max = 20, message = "user name cannot exceed 20 characters") @ Pattern (regexp = "^ [\\ u4E00 -\\ u9FA5A-Za-z0-9\ *] * $", message = "user nickname limit: up to 20 characters, including text, letters and numbers") private String username / * * Mobile number * / @ NotBlank (message = "the mobile number cannot be empty") @ Pattern (regexp = "^ [1] [3LINGEI] [3LING 5Jing 5Jing 5Jing 7Jing 8Jing 9] [0-9] {9} $", message = "incorrect format of Mobile ID") private String mobile; / * * gender * / private String sex / * * mailbox * / @ NotBlank (message = "contact mailbox cannot be empty") @ Email (message = "incorrect mailbox format") private String email; / * * password * / private String password; / * * creation time * / @ Future (message = "time must be future") private Date createTime;} 1.2. Scheme
Can not use its annotations, but we can use its method, the following I wrote an example of using Java code to verify parameters, throw a brick to attract jade, can not be directly used in their own system, oh, want to use, please combine their own system encapsulation method, I intend to make the form of annotations, use spring aop to cut my service layer, the effect is similar to the controller layer
1.2.1. The main method import org.springframework.validation.annotation.Validated;import javax.validation.ConstraintViolation;import javax.validation.Validation;import javax.validation.Validator;import javax.validation.ValidatorFactory;import java.util.Date;import java.util.Set;import java.util.stream.Stream;/** * @ author laoliangliang * @ date 15:19 on 2019-10-22 * / public class ValidLearn {public static void main (String [] args) {ValidLearn learn = new ValidLearn () Learn.testValid (new Order (). SetIdcard ("33062119981012361X"). SetName ("") .setCreateDate (new Date ());} public void testValid (@ Validated Order order) {ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory (); Validator validator = validatorFactory.getValidator (); / / packet Insert.class then id is null and does not check Set validate = validator.validate (order, Insert.class) Stream.of (validate) .forEach (action-> {for (ConstraintViolation orderConstraintViolation: action) {String message = orderConstraintViolation.getMessage (); System.out.println (message);}});} 1.2.2. Entity class / * * @ author laoliangliang * @ date 2019-10-21 16:44 * / @ Data@Accessors (chain = true) public class Order {@ NotNull (message = "id cannot be empty", groups = Update.class) private Long id; @ NotEmpty (message = "name is not null", groups = Insert.class) private String name; @ Future (message = "time after necessary") private Date createDate @ IdCardValid (message = "idcard is invalid") private String idcard;}
The above two codes can verify the annotation of the entity class object and print the message that the verification fails, and can be modified to throw an exception if there is a check error message.
The code also covers some details, such as group grouping and custom annotations
1.2.3. Group grouping import javax.validation.groups.Default;/** * @ author laoliangliang * @ date 16:32 on 2019-10-22 * / public interface Update extends Default {} import javax.validation.groups.Default;/** * @ author laoliangliang * @ date 2019-10-22 16:32 * / public interface Insert extends Default {}
I use Insert.class in my example code, which means that the comments that exist in this group will only work when the insert action is done, so the comments that are not passed by id and the id is not empty will not work.
1.2.4. Custom Annotation import javax.validation.ConstraintValidator;import javax.validation.ConstraintValidatorContext;import java.util.regex.Matcher;import java.util.regex.Pattern / * * @ author laoliangliang * @ date, 2019-10-22 15:55 * / public class IdCardValidator implements ConstraintValidator {private Pattern pattern = Pattern.compile ("^ [1-9]\\ d {7} ((0\\ d) | (1 [0-2])) ([0 | 1 | 2]\\ d) | 3 [0-1])" + "\ d {3} $| ^ [1-9]\\ d {5} [1-9]\ d {3} ((0\\ d) | (1 [0-2])) (([0 | 1 | 2]\\ d) | 3 [0-1])\\ d {3} ([0-9] | X) $") @ Override public void initialize (IdCardValid idCardValid) {} @ Override public boolean isValid (Object o, ConstraintValidatorContext constraintValidatorContext) {Matcher matcher = pattern.matcher (o.toString ()); return matcher.matches () }} / * @ author laoliangliang * @ date, 2019-10-22 15:53 * / @ Documented@Target ({ElementType.PARAMETER,ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) @ Constraint (validatedBy = IdCardValidator.class) public @ interface IdCardValid {String message () default "ID card is invalid"; Class [] groups () default {}; Class
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.