In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use @ Valid+BindingResult for controller parameter verification". In daily operation, I believe many people have doubts about how to use @ Valid+BindingResult for controller parameter verification. Xiaobian consulted all kinds of data and sorted out simple and useful operation methods. I hope it will be helpful for you to answer the doubt of "how to use @ Valid+BindingResult for controller parameter verification"! Next, please follow the editor to study!
@ Valid+BindingResult for controller parameter verification
Since controller is the first layer of the call, frequent parameter verification will be completed here. It is common to have non-null check, type check, and so on. The following pseudocode is commonly used:
Public void round (Object a) {if (a.getLogin ()) = = null) {return "Mobile number cannot be empty!" ;}}
However, there will be many locations of the calling object, and the mobile phone number cannot be empty, so we will think of pulling out the verification method to avoid duplicate code. However, there is a framework that allows us to verify parameters through annotations.
First set up a scene, in order to add animals to the zoo, the animal object is as follows, the time node is about 3030, we think that animals can log on to the animal-specific system, so there is password that is their own login password.
Public class Animal {private String name; private Integer age; private String password; private Date birthDay;}
Call the controller layer that creates the animal as follows, which is concise and clear. Print the information and return it directly.
@ RestController@RequestMapping ("/ animal") public class AnimalController {@ PostMapping public Animal createAnimal (@ RequestBody Animal animal) {logger.info (animal.toString ()); return animal;}}
The test class that forges the Mvc call.
@ RunWith (SpringRunner.class) @ SpringBootTestpublic class TestAnimal {private final static Logger logger = LoggerFactory.getLogger (TestAnimal.class); @ Autowired private WebApplicationContext wac; private MockMvc mockMvc; @ Before public void initMock () {mockMvc = MockMvcBuilders.webAppContextSetup (wac) .build () } @ Test public void createAnimal () throws Exception {String content = "{\" name\ ":\" elephant\ ",\" password\ ": null,\" birthDay\ ":" + System.currentTimeMillis () + "}" String result = mockMvc.perform (MockMvcRequestBuilders.post ("/ animal") .content (content) .contentType (MediaType.APPLICATION_JSON_UTF8)) .andexpect (MockMvcResultMatchers.status () .isOk ()) .andReturn () .getResponse () .getContentAsString (); logger.info (result);}}
The above code is based on the built springboot project. Students who want to build it can refer to build a https://www.yisu.com/article/226998.htm.
Code analysis, date format parameters are recommended to use timestamp transmission, the above birthDay pass "2018-05-08 20:00:00", will throw a date conversion exception, interested students can try.
Because the password is very important, the password is required. Add the @ NotBlank annotation to the password as follows:
@ NotBlankprivate String password
However, the light plus check annotation does not work, and you need to add @ Valid annotation to the method parameters as follows:
@ Valid @ RequestBody Animal animal
At this point, the test method is executed, an exception is thrown, and the return status is 400:
Java.lang.AssertionError: Status
Expected: 200
Actual: 400
At org.springframework.test.util.AssertionErrors.fail (AssertionErrors.java:54)
At org.springframework.test.util.AssertionErrors.assertEquals (AssertionErrors.java:81)
Indicates that the non-null check for password has taken effect, and an exception is thrown directly. If you do not want to throw an exception and want to return the verification information to the frontend, you need to use BindingResult at this time. Modify the method of creating the animal and add the BindingResult parameter:
@ PostMapping public Animal createAnimal (@ Valid @ RequestBody Animal animal, BindingResult bindingResult) {if (bindingResult.hasErrors ()) {bindingResult.getAllErrors () .forEach (o-> {FieldError error = (FieldError) o; logger.info (error.getField () + ":" + error.getDefaultMessage ());} logger.info (animal.toString ()); return animal }
At this point, when you execute the test, you can see the error message in the log:
2018-05-09 00 INFO 5915 37 453 INFO 14044-[main] c.i.s.d.web.controller.AnimalController: password:may not be empty
In order to meet our coding needs, we need to modify the code, 1. Cannot return animal directly. two。 The prompt message returned must be readable by the user.
The controller method is modified to pass the message or error message after a successful request through the Map object.
@ PostMapping public Map createAnimal (@ Valid @ RequestBody Animal animal, BindingResult bindingResult) {logger.info (animal.toString ()); Map result = new HashMap (); if (bindingResult.hasErrors ()) {FieldError error = (FieldError) bindingResult.getAllErrors (). Get (0); result.put ("code", "400"); / / error code 400 result.put ("message", error.getDefaultMessage ()) / / error message return result;} result.put ("code", "200"); / / 200 result.put ("data", animal) successfully encoded; / / data returned successfully return result;}
The password prompt returned is as follows:
@ NotBlank (message = "password cannot be empty!") Private String password
Execute the test method and return the result
Com.imooc.security.demo.TestAnimal: {"code": "400,400", "message": "password cannot be empty!" }
Finally, post one and set the password value to return the information of success.
Com.imooc.security.demo.TestAnimal: {"code": "200"," data ": {" name ":" elephant "," age ": null," password ":" lalaland "," birthDay ": 1525799768955}
Due to the limited space, a custom annotation implementation will be implemented based on this example next time, and this article ends here.
Parameter check import com.example.demo.pojo.Student;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; import javax.validation.Valid of Controller layer method @ Controller@RequestMapping ("/ stu") public class StudentController {@ PostMapping ("/ addStu") @ ResponseBody public String addStudent (@ Valid Student student) {System.out.println ("Store student objects"); System.out.println (student); return "ok";}} import org.hibernate.validator.constraints.Length; import javax.validation.constraints.Max;import javax.validation.constraints.Min;import javax.validation.constraints.NotEmpty Import javax.validation.constraints.NotNull; public class Student {@ NotNull (message = "null value passed in, please pass the value") @ Min (value = 0ther message = "there is an error in the incoming student score, the score is between 0 and 100,00") @ Max (value = 100centence message = "the incoming student score is incorrect, the score is between 0,100") private Integer score @ NotEmpty (message = "passing an empty string, please pass a value") @ NotNull (message = "passing a null value, please pass a value") private String name; @ NotNull (message = "passing a null value, please pass a value") @ NotEmpty (message = "an empty string is passed in, please pass a value") @ Length (min = 1181 max = 11pm message = "wrong number, length should be 11 digits") private String mobile Public Integer getScore () {return score;} public void setScore (Integer score) {this.score = score;} public String getName () {return name;} public void setName (String name) {this.name = name;} public String getMobile () {return mobile;} public void setMobile (String mobile) {this.mobile = mobile } @ Override public String toString () {return "Student {" + "score=" + score + ", name='" + name +'\'+ ", mobile='" + mobile +'\'+'}';}} Global uniform exception interceptor import org.springframework.validation.BindException;import org.springframework.web.bind.annotation.ControllerAdvice Import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody; @ ControllerAdvicepublic class GlobalExceptionInterceptor {@ ExceptionHandler (value = Exception.class) @ ResponseBody public String exceptionHandler (Exception e) {String failMessage=null; if (e instanceof BindException) {failMessage= ((BindException) e) .getBindingResult () .getFieldError () .getDefaultMessage ();} return failMessage;}}
When we pass in an incorrect parameter, it will be caught by the exception interceptor and return the error message to us.
At this point, the study on "how to use @ Valid+BindingResult for controller parameter 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.