In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
What is the role of Validation in SpringMVC, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Use the Validator interface for authentication
A Validator interface is provided in SpringMVC through which we can define our own validation of entity objects. Let's take a look at an example. Suppose we now have an entity class User that needs to be validated, with the following code:
Public class User {private String username; private String password; public String getUsername () {return username;} public void setUsername (String username) {this.username = username;} public String getPassword () {return password;} public void setPassword (String password) {this.password = password } public String toString () {return username + "," + password;}}
So what do we do when we need to use the Validator interface provided by SpringMVC to validate the entity class? At this point, we should provide an implementation class for Validator and implement the supports method and validate method of the Validator interface.
The Supports method is used to determine whether the current Validator implementation class supports verifying the entity class that currently needs to be verified. Only when the return result of the supports method is true, the validate method of the Validator API implementation class will be called to verify the entity class that currently needs to be verified. Assuming that we need to verify that neither the username nor the password of the User class can be null, give the code first and explain it later. Here we define a UserValidator with the following code:
Import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class UserValidator implements Validator {public boolean supports (Class clazz) {/ / TODO Auto-generated method stub return User.class.equals (clazz) } public void validate (Object obj, Errors errors) {/ / TODO Auto-generated method stub ValidationUtils.rejectIfEmpty (errors, "username", null, "Username is empty."); User user = (User) obj; if (null = = user.getPassword () | | ".equals (user.getPassword ()) errors.rejectValue (" password ", null," Password is empty. ");}}
In the above code, we defined in the supports method that the UserValidator only supports validation of the User object. In the validate method, we verify that the username and password of the User object are not empty. Here the empty includes null and an empty string. The ValidationUtils class is a utility class provided in Spring. Errors is the object that Spring uses to store error messages.
We have defined a UserValidator to validate the User class, but at this time UserValidator cannot validate the User object because we have not yet told Spring that UserValidator should be used to validate the User object. In SpringMVC we can use DataBinder to set the Validator that the current Controller needs to use. Let's take a look at the following code:
Import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.DataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; @ Controller public class UserController {@ InitBinder public void initBinder (DataBinder binder) {binder.setValidator (new UserValidator ()) @ RequestMapping ("login") public String login (@ Valid User user, BindingResult result) {if (result.hasErrors ()) return "redirect:user/login"; return "redirect:/";}}
In the above code, we can see that we have defined a UserController. The Controller has a processor method login that handles the login operation, which needs to receive a User object sent by the client. We just want to use the previous UserValidator to verify the User object. First of all, we can see that the parameter user received by our login method is marked with @ Valid, where @ Valid is defined in the JSR-303 standard, and I'm using Hibernate Validation's implementation of it. Here we must use @ Valid to mark the parameter user that we need to verify, otherwise Spring will not verify it. In addition, our processor method must give a parameter containing Errors, which can be Errors itself or its subclass BindingResult. Using the Errors parameter tells Spring that errors in the data validation of the form object will be handled by ourselves, otherwise Spring will directly throw an exception, and this parameter must be next to the @ Valid parameter, that is, next to the parameter to be verified. This means that we have as many @ Valid parameters as we need to have as many corresponding Errors parameters, and they correspond one to one. It was mentioned earlier that we can specify the Validator we need to use through DataBinder, and we can see that in the above code, we set the Validator that the current Controller needs to use is UserValidator through the method initBinder of the @ InitBinder tag. In this way, when we request the processor method login, we will use the UserValidator set by DataBinder to verify the current form object User, first of all, we will use the supports method of UserValidator to determine whether it supports the verification of the User object, if so, call the validate method of UserValidator, and store the relevant verification information in the current Errors object. Then we can do different operations in our processor methods depending on whether there is a check exception message. In the above code, we define to jump to the landing page when there is an abnormal message. So we can display these error messages through the errors tag on the login page.
We know that the method through the @ InitBinder tag in the Controller class is executed only when the current Controller is requested, so the Validator defined in it can only be used in the current Controller. If we want a Validator to work on all Controller, we can set it through the initBinder method of WebBindingInitializer. In addition, the global Validator can also be specified through the validator property of mvc:annotation-driven in the configuration file of SpringMVC. The code is as follows:
Use JSR-303 Validation for authentication
JSR-303 is a specification for data validation. I will not talk about this specification here, but will only talk about the application of JSR-303 in SpringMVC. JSR-303 is only a specification, and Spring does not implement this specification, so when we need to use JSR-303 in SpringMVC, we need to provide an implementation of JSR-303 specification. Hibernate Validator implements this specification, and here I will use it as an implementation of JSR-303 to explain SpringMVC's support for JSR-303.
JSR-303 's validation is based on annotations, and a series of restriction annotations have been defined internally. We only need to mark these annotations on the attributes of the entity class that needs to be validated or on their corresponding get methods. Let's take a look at the following code for an entity class User that needs to be verified:
Import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; public class User {private String username; private String password; private int age; @ NotBlank (message= "username cannot be empty") public String getUsername () {return username;} public void setUsername (String username) {this.username = username } @ NotNull (message= "password cannot be null") public String getPassword () {return password;} public void setPassword (String password) {this.password = password;} @ Min (value=10, message= "minimum age is 10") public int getAge () {return age } public void setAge (int age) {this.age = age;}}
We can see that we have added a note to the corresponding get methods of username, password, and age. These annotations are the limitations defined in JSR-303, where @ NotBlank is an extension of Hibernate Validator. It is not difficult to find that it is much easier to use JSR-303 for verification than to use the Validator interface provided by Spring. We know that annotations only play a marked role, it will not directly affect the operation of the code, it needs to be recognized by some classes in order to play a limiting role.
When using SpringMVC, we only need to put the jar package corresponding to the implementer of JSR-303 into classpath, and then introduce MVC Namespace into the configuration file of SpringMVC, plus mvn:annotation-driven/, we can easily use JSR-303 to verify entity objects. After adding mvn:annotation-driven/, Spring automatically detects the JSR-303 provider under classpath and automatically enables support for JSR-303, putting the corresponding verification error message into the Errors object of Spring. At this point, the configuration file for SpringMVC is as follows:
Next, let's define a Controller that uses the User object as the parameter receiver. The code is as follows:
Import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; @ Controller public class UserController {@ RequestMapping ("login") public String login (@ Valid User user, BindingResult result) {if (result.hasErrors ()) return "user/login"; return "redirect:/";}}
In this way, when we request login.do without any parameters, we cannot limit the validity of the attribute data of the entity object User, and then place the corresponding error message in the current Errors object.
The limitations of JSR-303 native support are as follows:
Limit description @ Null limit can only be null@NotNull limit must not be null@AssertFalse limit must be false@AssertTrue limit must be true@DecimalMax (value) limit must be a number not greater than the specified value @ DecimalMin (value) limit must be a number not less than the specified value @ Digits (integer,fraction) limit must be a decimal, and the number of digits of the integer cannot exceed integer The number of decimal places must not exceed the fraction@Future limit must be a future date @ Max (value) limit must be a number not greater than the specified value @ Min (value) limit must be a number not less than the specified value @ Past limit must be a past date @ Pattern (value) limit must conform to the specified regular expression @ Size (max,min) limit character length must be between min and max
In addition to the restriction types natively supported by JSR-303, we can also define our own restriction types. To define your own restriction type, we first have to define an annotation for that restriction type, and the annotation needs to be annotated with * * @ Constraint**. Now suppose we need to define a limit type that represents the amount, then we can define it as follows:
Import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import com.xxx.xxx.constraint.impl.MoneyValidator; @ Target ({ElementType.FIELD, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Constraint (validatedBy=MoneyValidator.class) public @ interface Money {String message () default "not in amount form" Class [] groups () default {}; 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.