In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "what is the principle of spring annotation verification". In daily operation, I believe many people have doubts about what the principle of spring annotation verification is. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubt of "what is the principle of spring annotation verification?" Next, please follow the editor to study!
I. introduction
There is no more to say about the importance of parameter validity verification, even if the front end has done the basic verification of the parameters, the back end still needs to be verified to prevent non-compliant data from entering the back end directly, or even cause the system to crash directly!
In this paper, combined with their own practical experience in the project, mainly practical, to verify the validity of the data to do a summary, do not understand friends can learn, at the same time can immediately practice to the project.
Let's use a few examples to demonstrate how to judge whether the parameters are legal or not.
2. Assertion verification
For the validation of parameters, the initial approach is relatively simple, customizing an exception class.
Public class CommonException extends RuntimeException {/ * * error code * / private Integer code; / * * error message * / private String msg; / /... set/get public CommonException (String msg) {super (msg); this.msg = msg;} public CommonException (String msg, Throwable cause) {super (msg, cause); this.msg = msg;}}
When judging that a parameter is illegal, throw an exception directly!
@ RestController public class HelloController {@ RequestMapping ("/ upload") public void upload (MultipartFile file) {if (file = = null) {throw new CommonException ("Please choose to upload file!") / /. }}
Then write a unified exception interceptor to handle the program that throws the exception.
This approach is more intuitive, if the current parameter to determine whether it is empty, but also to determine whether the length exceeds the maximum length, the code appears to be a little too much!
As a result, the bigwigs in the program world have come up with a more elegant and code-saving way to create an assertion tool class that is specifically used to determine whether parameters are legal, and if not, throw an exception!
/ * assertion tool class * / public abstract class LocalAssert {public static void isTrue (boolean expression, String message) throws CommonException {if (! expression) {throw new CommonException (message);}} public static void isStringEmpty (String param, String message) throws CommonException {if (StringUtils.isEmpty (param)) {throw new CommonException (message);}} public static void isObjectEmpty (Object object, String message) throws CommonException {if (object = = null) {throw new CommonException (message) }} public static void isCollectionEmpty (Collection coll, String message) throws CommonException {if (coll = = null | | (coll.size () = = 0)) {throw new CommonException (message);}
When we need to validate the parameters, the basic operation can be done directly through this class, as follows:
@ RestController public class HelloController {@ RequestMapping ("/ save") public void save (String name, String email) {LocalAssert.isStringEmpty (name, "user name cannot be empty!") ; LocalAssert.isStringEmpty (email, "mailbox cannot be empty!") / /. }}
Compared with the previous step, when there are more parameters to judge, the code is obviously much simpler!
For a tool class like this, spring also provides an assertion tool class called Assert, which you can use directly when developing!
III. Annotation verification
Using annotations to validate data is a great innovation in the java world, which not only makes the code concise, but also makes it very enjoyable to read!
3.1. Dependency package introduction
Let's take a look at the specific practice. Take the Spring Boot project as an example. If you need to use annotation verification, you can directly introduce the spring-boot-starter-web dependency package, and the dependency package related to annotation verification will be automatically entered into the project!
Org.springframework.boot spring-boot-starter-web
The lombok plug-in is also used when creating entity classes, so you also need to introduce the lombok dependency package!
Org.projectlombok lombok 1.18.4 provided
If it is an ordinary Java project, introduce the following dependency packages!
Org.hibernate.validator hibernate-validator 6.0.9.Final javax.el javax.el-api 3.0.0 org.glassfish.web javax.el 2.2.6
3.2. Annotation verification request object
Next let's create an entity User that simulates the request entity object when the user registers!
@ Data @ EqualsAndHashCode (callSuper = false) @ Accessors (chain = true) public class User {@ NotBlank (message = "user name cannot be empty!") Private String userName; @ Email (message = "incorrect mailbox format") @ NotBlank (message = "mailbox cannot be empty!") Private String email; @ NotBlank (message = "password cannot be empty!") @ Size (min = 8, max = 16 Magi message = "Please enter a password with a length of 8 to 16 digits") private String userPwd; @ NotBlank (message = "confirm that the password cannot be empty!") Private String confirmPwd;}
Create a register () registration interface method in the web layer, and add @ Valid to the request parameters, as follows:
@ RestController public class UserController {@ RequestMapping ("/ register") public boolean register (@ RequestBody @ Valid User user) {if (! user.getUserPwd (). Equals (user.getConfirmPwd () {throw new CommonException ("confirm that the password is different from the password, please confirm!") ;} / / Business processing. Return true;}}
Finally, customize an exception global handler to handle exception messages, as follows:
@ Slf4j @ Configuration public class GlobalWebMvcConfig implements WebMvcConfigurer {/ * Unified exception handling * @ param resolvers * / @ Override public void configureHandlerExceptionResolvers (List resolvers) {resolvers.add (new HandlerExceptionResolver () {@ Override public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {log.error ("[uniform exception interception] request encountered an exception It reads as follows: ", e) ModelAndView mv = new ModelAndView (new MappingJackson2JsonView ()); String uri = request.getRequestURI (); if (e instanceof CommonException) {/ / CommonExecption is the exception printWrite thrown by the custom exception class (CommonException) e). GetMsg (), ((CommonException) e). GetData (), uri, mv) } else if (e instanceof MethodArgumentNotValidException) {/ / MethodArgumentNotValidException is comment check exception class / / get note check exception information String error = ((MethodArgumentNotValidException) e). GetBindingResult (). GetFieldError () .getDefaultMessage (); printWrite (error,null, uri, mv) } else {printWrite (e.getMessage (), null, uri, mv);} return mv;}}) } / * exception encapsulates the corresponding result * @ param object * / private void printWrite (String msg, Object object, String uri, ModelAndView mv) {ResResult resResult = new ResResult (uri, object); if (msg! = null) {resResult.setMsg (msg) } if (log.isDebugEnabled ()) {log.debug ("[response] exception output result:" + JSONObject.toJSONString (resResult, SerializerFeature.WriteMapNullValue));} Map resultMap = BeanToMapUtil.beanToMap (resResult); mv.addAllObjects (resultMap);}}
Let's start the project and test it with postman to see how it works.
Test whether the field is empty
Test whether the mailbox is legal
Test whether the password length meets the requirements
Test password and confirm password are the same
3.3. Comment verification request parameters
We have described the verification method of the request object above, so is it equally effective to validate the request parameters directly on the method?
In order to believe what you see, let's simulate the method to validate the request parameters and see what the result is.
Create a new query interface query, as follows
@ RestController public class UserController {@ PostMapping ("/ query") public boolean query (@ RequestParam ("userId") @ Valid @ NotBlank (message = "user ID cannot be empty") String userId) {return true;}}
Try using postman request. The default parameter for userId is null. The result is as follows:
It is clear that the parameter annotation verification in the query () method is invalid!
When we add @ Validated annotations to the UserController class!
@ RestController @ Validated public class UserController {@ PostMapping ("/ query") public boolean query (@ RequestParam ("userId") @ Valid @ NotBlank (message = "user ID cannot be empty") String userId) {return true;}}
Use postman to request another try, and the result is as follows!
It is clear that the annotations are validated and an exception ConstraintViolationException is thrown!
When the @ Validated parameter acts on a class, it tells Spring that the request parameter in the method can be verified!
So in actual development, we can use a combination of @ Validated and @ Valid annotations to verify the request parameters and request objects in the method!
At the same time, the @ Validated and @ Valid annotations don't just validate the controller level, they can validate any Spring component, such as the Service layer method input parameter!
@ Service @ Validated public class UserService {public void saveUser (@ Valid User user) {/ / dao insert}}
3.4. Custom annotation verification
By default, the dependency package has provided us with a lot of validation annotations, as follows!
Check comments provided by JSR!
Check comments provided by Hibernate Validator
But in some cases, such as gender, we may need to verify the parameter ourselves, and we can also customize an annotation to complete the verification of the parameter, as follows!
Create a new Sex annotation, where the SexValidator class refers to the specific parameter validation class
@ Target ({FIELD}) @ Retention (RUNTIME) @ Constraint (validatedBy = SexValidator.class) @ Documented public @ interface Sex {String message () default "gender value is not within the optional range"; 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.