As a service-side development, verifying the legitimacy of the front-end incoming parameters is an essential step, but the validation parameter is basically a physical activity, and the redundant code is numerous, and also affects the readability of the code, so is there a more elegant way to solve this problem?
The simple question of course has been met and solved by the great God, this article mainly discusses the better method to solve the validation parameters based on Spring-boot: using VALIDATOR-API to validate parameters.
spring-boot-starter-web
there is a package in the package hibernate-validator
, it provides a series of methods to verify various parameters, so Spring-boot has helped us figure out how to solve the problem.
This article describes three ways to validate parameters for SPRING-MVC in Spring-boot.
(a): This method is mostly available on the web, assuming that our restful interface accepts a GradeAndClassroomModel
type of object, and that the class is defined as
@data Public class Gradeandclassroommodel {@Range (min = 1, max = 9, message = "grade can only be from 1-9") private int Grade @range (min = 1, max = 99, message = " class only from 1-99 ") private int classroomnumber;}
By using a validator
series of annotations provided, such as in this example @Range
, you can represent the scope of the parameter and the prompt message when the error occurs. There are many other annotations that are not listed here
Then the code for our controller layer is
@RequestMapping(value = "/paramErrorTest", method = RequestMethod.GET)public String paramErrorTest( @Valid @ModelAttribute GradeAndClassroomModel gradeAndClassroomModel, BindingResult result) { return classroomService.getTeacherName(gradeAndClassroomModel.getGrade(), gradeAndClassroomModel.getClassroomNumber());}
Where the validation error occurs, there is an error message inside the result object, which can then be processed on its own.
(b): For the above example, it will be said that the two parameters, why should they be used as objects? Will it be too much trouble? Indeed, if there are only a handful of objects, write the parameters directly to the controller layer and then validate it at the controller layer.
@RequestMapping (value ="/teachername", method = requestmethod.get) public String teachername ( @Range (min = 1, max = 9, message = Span class= "hljs-string" > "grade only from 1-9") @RequestParam (name = " Grade ", required = true) int grade, @Min (value = 1, message = "class min only 1") @Max (value = 99, message = Span class= "hljs-string" > "class Max only") @RequestParam (name = " Classroom ", required = true) int classroom) {return Classroomservice.getteachername (grade, classroom);}
Would validator
it be possible to simply remove the provided annotations to write to the request parameters? The answer is wrong, why is it not successful to validate parameters? For specific reasons, please refer to the official documentation: http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/htmlsingle/# Validation-beanvalidation-spring-method
The above document is very clear, so we need to create a bean
@Beanpublic MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor();}
Then add annotations to the class method@Validated
@RestController@RequestMapping("/spring-boot/classroom")@Validatedpublic class ClassroomController { ...}
Annotations that are not in effect before, etc., are then @Range
@Min
@Max
validator
available in the package.
(c) It is estimated that there will be people asking if the validator
annotations in the package do not meet our needs, can we define the logic of parameter validation ourselves. The answer is yes, we can use
@Documented@retention (Retentionpolicy.runtime) @Target ({ElementType. PARAMETER,ElementType. FIELD}) @Constraint (validatedby = {validator .class}) public @interface paramvalidator {string message () default" Span class= "Hljs-selector-tag" >parameter error! "; class<?>[] groups () default {}; CLASS<? extends payload> [] payload () Default {};}
And
public class Validator implements ConstraintValidator<ParamValidator, Object> { ...}
A combination of customizations, specific examples of other articles on the web is a lot of, here is not a detailed example, but the final use of the time is
@RequestMapping (value ="/paramvalidator", method = requestmethod.get) public String paramvalidator ( @ParamValidator (isrequired = true, desc = "grade", Range = "int:1~9", message = "grade only from 1-9") @ Requestparam (name = "grade", required = true) int grade, @ Paramvalidator (isrequired = true, desc = "class", Range = "int:1~99", message = "class can only be from 1-99") @RequestParam (name = " classroom ", required = true) int classroom) {return classroomservice.getteachername (grade, classroom);}
Also do not forget that the 方法二
bean mentioned in the inside MethodValidationPostProcessor
, if the bean is not initialized, the custom authentication method will not be executed. The validation logic is invalidated.
Is the code logic better, clearer, and more elegant than validating the requested parameters in such a way as to write annotations? Will the meaning of the expression be better and clearer? And there is no similar validation code that repeats a lot.
Ps: The code here is based on the SPRING-MVC framework, if someone does not use SPRING-MVC as a rest framework, but instead uses jersey as the rest framework, there may be some details that need to be adjusted, but these three scenarios should be compatible.
Finally, if you feel that what you are talking about can help you, and want to learn more and learn more in depth, you are welcome to Dabigatran 632109190 for discussion and study.
Using VALIDATOR-API to verify the parameters of the Spring-boot