springmvc--Data Conversion & Data formatting & data validation

Source: Internet
Author: User

First, the data binding process
    • 1. The Spring MVC main framework passes the ServletRequest object and the instance of the target method to the Webdatabinderfactory instance to create the DataBinder instance object
    • 2. DataBinder calls the Conversionservice component assembled in the Spring MVC context to perform data type conversion, data formatting work. Populate the request information in the Servlet into the incoming parameter object
    • 3. Call the Validator component to verify the data legitimacy of the incoming parameter object that already has the request message bound, and eventually generate the data-bound result BindingData Object
    • 4. Spring MVC Extracts the Bindingresult and the checksum error objects from the, assigning them to the response of the processing method

Spring MVC parses the target processing method through the reflection mechanism, and binds the request message to the incoming parameter of the processing method. The core component of data binding is DataBinder, which operates as follows:

SOURCE Analysis
    • Break point debugging at the property setter method of the JavaBean object
    • Enter org.springframework.web.method.annotation.modelattributemethodprocessor#resolveargument on the Debug page
 Public FinalObject resolveargument (methodparameter parameter, Modelandviewcontainer Mavcontainer, nativewebrequest request, Webdatabinderfactory binderfactory)throwsException {String name=modelfactory.getnameforparameter (parameter); Object attribute= Mavcontainer.containsattribute (name)? Mavcontainer.getmodel (). Get (name): This. CreateAttribute (name, parameter, binderfactory, request);//Create a Binderd objectWebdatabinder Binder =Binderfactory.createbinder (Request, attribute, name); if(Binder.gettarget ()! =NULL) {       //Binding of data        This. Bindrequestparameters (binder, request); //verifying the completion of the data         This. Validateifapplicable (binder, parameter); if(Binder.getbindingresult (). HasErrors ()
&& This. isbindexceptionrequired (binder, parameter)) { Throw Newbindexception (Binder.getbindingresult ()); }} Map Bindingresultmodel=Binder.getbindingresult (). Getmodel (); mavcontainer.removeattributes (Bindingresultmodel); Mavcontainer.addallattributes (Bindingresultmodel); returnBinder.gettarget (); }
    • To view the properties of a binder object

    • You can see that the binder contains the Conversionservice and Validators properties, which handle type conversions and data validation, respectively.
Second, data conversion
    • There are a number of converters built into the Spring MVC context to accomplish most of the conversion work for Java types.
    • Conversionservice converters =

Custom type Converters

Conversionservice is the core interface of the Spring type conversion system.

    • You can use Conversionservicefactorybean to define a conversionservice in the Spring IOC container. Spring will automatically identify the conversionservice in the IOC container and use it for data conversion in the case of Bean attribute configuration and Spring MVC processing method entry binding.
    • Custom type converters can be registered through the Converters property of Conversionservicefactorybean
Third, the format of data
    1. Add the Birthday (birthday) input box to the form, and in the JavaBean Brith property, the type of the property is Java.util.Date
    2. Page 400 error when submitting form, data cannot be submitted to target method
    3. Cause: The birthday of the input box is not formatted

Workaround:

annotation on the birth property of the JavaBean object

@DateTimeFormat (pattern = "Yy-mm-dd"private Date birth;
①, date formatting

@DateTimeFormat Annotations can annotate java.util.Date, Java.util.Calendar, Java.long.Long time types:

    • Pattern Property: Type is a string. Specifies the mode for parsing/formatting field data, such as: "Yyyy-mm-dd hh:mm:ss"
    • ISO attribute: type is datetimeformat.iso. Specifies the ISO mode for parsing/formatting field data, including four types: Iso.none (not used)-default, ISO. DATE (YYYY-MM-DD), ISO. Time (HH:MM:SS. SSSZ), ISO. Date_time (Yyyy-mm-dd hh:mm:ss. SSSZ)
    • Style property: String type. Specifies the format of datetime by style, consisting of two-bit characters, the first digit is the format of the date, the second represents the time format: S: Short Date/Time format, M: Medium Date/Time format, L: Long Date/Time format, F: Full date/Time format,-: Ignore date or time format
②, numeric formatting

@NumberFormat can label a property of a similar number type, which has two mutually exclusive properties:

    • Style: Type is numberformat.style. Used to specify style types, including three types: Style.number (normal numeric type), style.currency (currency type), style.percent (Percent type)
    • Pattern: type String, custom style, such as patter= "#,###";
③, source analysis
    • There are many formatting processors built into the Spring MVC context that can be used to format most Java data types.
    • Conversionservice converters =

    • The input/output of a Property object is formatted, and it remains essentially a category of "type conversion".
    • Spring defines a Formattingconversionservice implementation class that implements the Conversionservice interface in the format module, which extends the Genericconversionservice, Therefore, it has both the function of type conversion and the function of formatting.
    • Formattingconversionservice has a Formattingconversionservicefactroybean factory class, which is used to construct the former in the Spring context

Formattingconversionservicefactroybean internal has been registered:

    • Numberformatannotationformatterfactroy: Support for using @NumberFormat annotations for attributes of numeric types
    • Datetimeformatannotationformatterfactroy: Support for using @DateTimeFormat annotations on properties of date types
    • Once the Formattingconversionservicefactroybean is assembled, annotations can be used in the Spring MVC input binding and model data output.
    • The Conversionservice instance created by default is Formattingconversionservicefactroybean
④, custom data type formatting & data Conversion
<Mvc:annotation-drivenConversion-service= "Conversionservice"></Mvc:annotation-driven>            <!--Configure Conversionservice -    <BeanID= "Conversionservice"class= "Org.springframework.format.support.FormattingConversionServiceFactoryBean">        < Propertyname= "Converters">            <Set>                <refBean= "Custom type format & Transform implementation class"/>            </Set>        </ Property>        </Bean>
Four, data verification

JSR 303 is the standard framework that Java provides for the validation of Bean data, which is already contained in Java EE 6.0. JSR 303 Specifies a validation rule by annotating annotations on bean properties similar to standards such as @NotNull, @Max, and validates the bean with a standard authentication interface

Hibernate Validator Extended Annotations:

    • Hibernate Validator is an implementation of JSR 303 that supports the following extended annotations in addition to supporting all standard checksum annotations
Verification process

①. Using the JSR 303 validation Standard
②. Add jar Package for Hibernate validator Validation Framework

hibernate-validator-5.0.0. Cr2.jarhibernate-validator-annotation-processor-5.0.0. Cr2.jarclassmate-0.8.0. Jarjboss-logging-3.1.1. Ga.jarvalidation-api-1.1.0.cr1.jar

③. Add <mvc:annotation-driven/> In the SPRINGMVC configuration file
④. Need to add corresponding annotations on the Bean's properties

 PackageCom.nchu.mybatis.bean;ImportOrg.hibernate.validator.constraints.Email;ImportOrg.hibernate.validator.constraints.NotEmpty;ImportOrg.springframework.format.annotation.DateTimeFormat;Importjava.util.Date;/*** Created by yangshijing on 2017/12/4 0004.*/ Public classEmployee {PrivateInteger ID; PrivateString LastName; @EmailPrivateString Email; PrivateString Gender; PrivateInteger DeptID; @DateTimeFormat (Pattern= "Yy-mm-dd")    PrivateDate Birth;  PublicEmployee () {} PublicEmployee (string email, string gender, Integer ID, string Lastname,integer deptid) { This. email =email;  This. Gender =gender;  This. ID =ID;  This. LastName =LastName;  This. DeptID =DeptID; }     PublicDate Getbirth () {returnbirth; }     Public voidSetbirth (Date birth) { This. Birth =birth; }     PublicInteger Getdeptid () {returnDeptID; }     Public voidSetdeptid (Integer deptid) { This. DeptID =DeptID; }     PublicString Getemail () {returnemail; }     Public voidsetemail (String email) { This. email =email; }     PublicString Getgender () {returngender; }     Public voidSetgender (String gender) { This. Gender =gender; }     PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString Getlastname () {returnLastName; }     Public voidsetlastname (String lastName) { This. LastName =LastName; } @Override PublicString toString () {return"employee{" + "id=" + ID + ", lastname= '" + lastName + "\" + ", email= '" + E Mail + ' \ ' + ', gender= ' + gender + ' \ ' + ', birth= "+ Birth + '} '; }}
View Code

⑤. Adding @Valid annotations before the target method bean type

 /**   * Add Employee interface *   @param   employee *   @return  */  @RequestMapping (value  = "/emp", method=  Requestmethod.post)  public  String Save ( @Valid Employee employee, Map<string,object> Map) { try  {employeeservice.saveemp (employee);  catch   (Exception e) {E.printstacktra        CE ();     return  "redirect:/employee/getemps" ; }

⑥, the form email item does not enter the email format, cannot access to the target method, and prints the error message in the console

springmvc--Data Conversion & Data formatting & data validation

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.