SPRINGMVC Validation Introduction--Very detailed

Source: Internet
Author: User
Tags bind min stub valid xmlns

Data validation on the client side of any application is not safe and effective, which requires us to validate the validity of the data on the server at the time of development. SPRINGMVC itself to the data on the service side of the calibration has a good support, it can be submitted to the service side of the data according to our prior agreement for data validation, for unqualified data information SPRINGMVC will be in the wrong object, These error messages can also be displayed on the front-end JSP page via the tags provided by SPRINGMVC. validating using the Validator interface

A validator interface is provided in SPRINGMVC that allows us to define our own validation of entity objects. Next look at an example.

Let's say we now have an entity class user that needs to be validated, and its code looks like this: 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 verify the entity class? At this time we should provide a validator implementation class, 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 validated, only if the Supports method returns TRUE. The Validate method of the validator interface implementation class is called to validate the entity class that currently needs to be validated. This assumes that we need to verify that the username and password of the user class are not empty, give their code first, and then explain them later. Here we define a uservalidator, whose code is as follows:

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 have defined in the Supports method that the Uservalidator only supports validating the user object. In the Validate method we verify that the username and password of the user object are not empty, where empty includes both null and empty string cases. The Validationutils class is a tool class provided in spring. Errors is the object that spring uses to store error messages.

We have defined a uservalidator that validates the user class, but at this point uservalidator cannot validate the user object because we have not yet told Spring that it should use Uservalidator to validate the user object. In SPRINGMVC we can use DataBinder to set the validator that the current controller needs to use. First look at the following section of 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, which has a handler method that handles the login operation login, which needs to receive a user object sent by the client, We're just going to use the previous Uservalidator to verify the user object. First we can see that our login method receives the parameter user is annotated with @valid, here the @valid is defined in the JSR-303 standard, I use the hibernate validation to its implementation. Here we have to use @valid to annotate the parameter user we need to verify , otherwise spring does not validate it. In addition, our processor method must be given a parameter containing errors , which can be the errors itself, or it can be its subclass Bindingresult, The errors parameter is used to tell spring that the error on the data validation of the form object will be handled by ourselves, otherwise spring will throw an exception directly, and this parameter must be next to the @valid parameter, which must be next to the parameter to be verified. This means that we have how many @valid parameters we need to have the corresponding errors parameters, which are one by one corresponding to each other. As mentioned earlier, we can use DataBinder to specify the validator to be used, We can see that in the above code we have set the Initbinder of the current controller using the @initbinder tag method Validator is uservalidator. This way, when we request the Processor method login, we will use the DataBinder set of Uservalidator to verify the current form object user, first of all through the Uservalidator supports method to determine whether it supports the user object checksum, If supported, call Uservalidator's Validate method and store the relevant checksum information in the current Errors object. Then we can do different things in our processor method depending on whether there is a check exception information. In the above code we have defined a jump to the landing page when there is an exception message. This allows us to display these error messages on the landing page via the Errors tab.

We know that the method of @initbinder tagging in the controller class is executed only when the current controller is requested, so the defined validator can only be used in the current controller. If we want a validator to work for all controllers, we can set it up by Webbindinginitializer's Initbinder method. In addition, global validator can also be specified in the SPRINGMVC configuration file through the Mvc:annotation-driven's validator property. The code looks like this: <?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"
Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/mvc
Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

<mvc:annotation-driven validator= "Uservalidator"/>

<bean id= "Uservalidator" class= "Com.xxx.xxx.UserValidator"/>

...
</beans>


validating with JSR-303 validation

JSR-303 is a specification of data validation, here I will not talk about this specification is going on, will only talk about the application of JSR-303 in Springmvc. JSR-303 is just 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 the JSR-303 specification, Hibernate Validator is the implementation of this specification, here I will use it as a JSR-303 implementation to explain SPRINGMVC to JSR-303 support.

The checksum of the JSR-303 is based on annotations, which define a series of restriction annotations internally, and we just need to mark the annotations on the attributes of the entity class that need to be validated or on the corresponding get method. Consider the following code for the entity class user that needs to be validated:
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= "User name 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 of 10")
public int getage () {
return age;
}

public void Setage (int.) {
This.age = age;
}

}

   We can see that we have added an annotation to the Get method for username, password, and age, which is the limit defined in JSR-303, where @notblank is hibernate Extension of the validator. It is not hard to see that using JSR-303 to perform a checksum is much simpler than using the validator interface provided by spring. We know that annotations are just a marker, it doesn't directly affect the running of the code, it needs to be recognized by some classes to be able to play a limiting role. When using SPRINGMVC, we simply put the jar package for the JSR-303 's implementation into CLASSPATH, and then introduce the MVC Namespace in the SPRINGMVC configuration file, plus <MVN: Annotation-driven/> can be very convenient to use the JSR-303 to verify the entity object. With <mvn:annotation-driven/>, Spring automatically detects the JSR-303 provider under CLASSPATH and automatically enables support for JSR-303. Put the corresponding checksum error message into Spring's errors object. The SPRINGMVC configuration file is as follows:

<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"
Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/mvc
Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

<mvc:annotation-driven/>
</beans>


We then define a controller that uses the user object as the receiver of the parameter, whose 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:/";
}

}

This way, when we request login.do without any parameters, we cannot pass the property data validity limit of the entity object user, and then place the corresponding error message in the current errors object.


There are several limitations to JSR-303 native support :

tr>

Restrictions

description

@Null

Limit can be Null

@Not Null

Restriction must not be null

@AssertFalse

td>

Limit must be false

@AssertTrue

Restrictions must be True

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.