In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "method of Spring Boot project parameter verification". The content of the article 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 method of Spring Boot project parameter verification".
Scene restoration
Simple business scenario simulation:
If you are now working on a score entry system, you happily write a background interface in the Spring Boot framework, which is used to receive Student objects from the foreground browser and insert them into the background database.
We define the incoming Student object as:
Public class Student {private String name; / / name private Integer score; / / exam score (out of 100s) private String mobile; / / phone number (11 digits)}
Then write a background interface for Post request to receive the Student object sent from the web page:
@ RestControllerpublic class TestController {@ Autowired private StudentService studentService; @ PostMapping ("/ add") public String addStudent (@ RequestBody Student student) {studentService.addStudent (student); / / store student objects in the database return "SUCCESS";}}
At this point, I think you must have noticed the loophole in the above code, because we did not do any data validation on the incoming Student object, such as:
One of the three fields in the Student object has been forgotten. What should I do for null? What if the score score of Student is written as 101points if you write it wrong? Student mobile11 bit mobile phone number, if you fill in it incorrectly, what if you write one more digit? ... Wait
Although these data are generally checked on the front-end page, as a rigorous and conscientious back-end development engineer, we certainly have to strictly verify every piece of data passed in, so how should we write it?
@ PostMapping ("/ add") public String addStudent (@ RequestBody Student student) {if (student = = null) return "the Student object passed is null, please pass the value"; if (student.getName ()) = = null | | ".equals (student.getName ()) return" the student name passed in is empty, please pass the value "; if (student.getScore () = = null) return" the incoming student score is null, please pass the value " If ((student.getScore () 100)) return "passed the wrong student score, the score should be between 0,100"; if (student.getMobile ()) = = null | | ".equals (student.getMobile ()) return" the incoming student phone number is empty, please pass the value "; if (student.getMobile (). Length ()! = 11) return" the incoming student phone number is incorrect, should be 11 digits " StudentService.addStudent (student); / / store student objects in the MySQL database return "SUCCESS";}
After writing, I feel a little sore in my hands and a little tired in my heart. This Student object is fine. After all, there are only 3 fields inside. What if a complex object has 30 fields? I can't imagine!
Divine notes and blessings
In fact, since the early version of the Spring framework, annotations have been used to easily provide us with the verification of various interactive data. For example, in the above example, we only need to add the corresponding annotations to the fields of the passed Student entity class to solve the problem:
Public class Student {@ NotNull (message = "the passed name is null, please pass the value") @ NotEmpty (message = "the passed name is an empty string, please pass the value") private String name / / name @ NotNull (message = "the incoming score is null, please pass the value") @ Min (value = 0mai message = "the incoming student's score is incorrect, the score should be between 0pp100") @ Max (value = 100pm message = "the incoming student's score is incorrect, the score should be between 0pp100") private Integer score / / score @ NotNull (message = "incoming phone is null, please pass value") @ NotEmpty (message = "incoming phone is empty string, please pass value") @ Length (min = 11, max = 11, message = "incoming phone number is incorrect, must be 11 digits") private String mobile; / / phone number}
Of course, at the same time, we also need to add the annotation @ Valid at the object entrance to start the validation of the incoming Student object:
@ PostMapping ("/ add") public String addStudent (@ RequestBody @ Valid Student student) {/ / Great! Previously, all kinds of complicated parameter calibration work were saved! One line of code does not need to write studentService.addStudent (student); / / stores the student object in the MySQL database return "SUCCESS";}
At this point, if an error is passed into a field, for example, when I pass data, the student's score is mispassed as 101, and the error details will be displayed when the API returns the result:
Of course, the principle of this matter, since the use of annotations, nothing more than a variety of Java reflection and other knowledge to achieve, interested partners can take this opportunity to study!
Unified interception of data anomalies
It feels good to use annotations to do unified data verification above, but the only drawback is that the returned results are too complicated to make the format we need. For example, I just want to dig out the error message of specific parameter verification and return it to the front end.
To do this, we configure a global unified exception interceptor for the project to format the return results of all data validations.
@ ControllerAdvice@ResponseBodypublic class GlobalExceptionInterceptor {@ ExceptionHandler (value = Exception.class) public String exceptionHandler (HttpServletRequest request, Exception e) {String failMsg = null; if (e instanceof MethodArgumentNotValidException) {/ / get the specific exception information of parameter verification prompt failMsg = ((MethodArgumentNotValidException) e). GetBindingResult (). GetFieldError (). GetDefaultMessage ();} return failMsg; / / directly spit back to the front end}}
As shown in the above code, we globally intercept the parameter verification exception MethodArgumentNotValidException, and only get the detailed Message information of the corresponding exception and spit it out to the frontend. In this case, the data returned to the frontend is much clearer:
Thank you for your reading, the above is the content of "the method of transmitting parameters and Verification of Spring Boot Project". After the study of this article, I believe you have a deeper understanding of the method of transmitting parameters and verification of Spring Boot projects, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.