SPRINGMVC Data Conversion & Data formatting & data validation

Source: Internet
Author: User
Tags string to number

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:

Data conversion

There are a number of converters built into the Spring MVC context to accomplish most of the conversion work for Java Types.

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 in the Bean attribute configuration and
The Spring MVC processing method is used to convert data by using it in the parameter binding.
Custom type converters can be registered through the Converters property of Conversionservicefactorybean

<mvc:annotation-driven conversion-service= "conversionservice"/> Registers the custom conversionservice into the context of spring MVC

<mvc:annotation-driven conversion-service= "conversionservice" ></mvc:annotation-driven><!--configuration Conversionservice--><bean id= "conversionservice" class= " Org.springframework.format.support.FormattingConversionServiceFactoryBean "><property name=" Converters " ><set><ref bean= "employeeconverter"/></set></property></bean>

Spring-supported Converters

Spring defines 3 types of converter interfaces that can be registered to Conversionservicefactroybean as a custom converter by implementing any of the converter interfaces:
converter<s,t>: Converting an S-type object to a T-type object
Converterfactory: the same series of multiple "homogeneous" Converter packaged Together. You can use this converter factory class if you want to convert an object of one type to an object of another type and its subclasses, such as converting a String to number and number subclasses (Integer, Long, Double, and so On)
Genericconverter: type conversions are based on contextual information from the source class object and the host class in which the target class object resides

1 @Component2  public classEmployeeconverterImplementsconverter<string, employee> {3 4 @Override5      publicEmployee convert (String source) {6         if(source! =NULL){7String [] vals = Source.split ("-");8             //gg-gg@atguigu.com-0-1059             if(vals! =NULL&& Vals.length = = 4){TenString LastName = vals[0]; oneString email = vals[1]; aInteger gender = Integer.parseint (vals[2]); -Department Department =NewDepartment (); -Department.setid (integer.parseint (vals[3])); the                  -Employee Employee =NewEmployee (NULL, lastName, email, gender, department); -System.out.println (source + "--convert--" +employee); -                 returnemployee; +             } -         } +         return NULL; a     } at  -}
View CodeAbout Mvc:annotation-driven

<mvc:annotation-driven/> will automatically register requestmappinghandlermapping, requestmappinghandleradapter With Exceptionhandlerexceptionresolver of three Beans.
The following support will also be provided:
Support for type conversion of form parameters using Conversionservice instances
Support for formatting data types using @NumberFormat annotation, @DateTimeFormat annotations
Support for JSR 303 validation of JavaBean instances using @Valid annotations
Support for using @RequestBody and @ResponseBody annotations

@InitBinder

The Webdatabinder object can be initialized by a method identified by the @InitBinder. Webdatabinder is a subclass of DataBinder that is used to complete bindings from form fields to JavaBean properties
@InitBinder method cannot have a return value, it must be declared as Void.
The parameters of the @InitBinder method are usually webdatabinder

Data formatting

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, So it has both the type conversion
function, but also has 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
Jodadatetimeformatannotationformatterfactroy: support for using @DateTimeFormat annotations on properties of date types
Once the Formattingconversionservicefactroybean is assembled, annotations are used to drive the Spring MVC input binding and the model data Output. <mvc:annotation-driven/> created by default
the Conversionservice instance is Formattingconversionservicefactroybean.

Date formatting

@DateTimeFormat annotations can annotate java.util.Date, java.util.Calendar, java.long.Long time Types:

@Past @datetimeformat (pattern= "yyyy-mm-dd") private Date birth;

Numeric formatting

@NumberFormat • Labels 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= "#,###";

@NumberFormat (pattern= "#,###,###.#") Private Float salary;
Data validation

JSR 303

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 a reference implementation of JSR 303, which supports the following extended annotations in addition to supporting all standard checksum annotations

Spring MVC Data validation

Spring 4.0 has its own independent data validation framework, while supporting the JSR 303 standard calibration Framework.
Spring Data binding, You can call the verification framework at the same time to complete the data validation Work. In Spring MVC, data validation can be done directly using Annotation-driven methods
Spring's Localvalidatorfactroybean not only implements the spring Validator interface, but also implements the Validator interface of the JSR 303. As long as a localvalidatorfactorybean is defined in the Spring container, it can be injected into the Bean that requires data validation.
Spring itself does not provide the implementation of JSR303, so it is necessary to place the jar package of the JSR303 's creator under the Classpath.

<mvc:annotation-driven/> will install good one localvalidatorfactorybean by default, by labeling @valid annotations on the processing Method's parameters to allow The work of Spring MVC to perform data validation after data binding is complete

How to verify? Annotations?
①. using the JSR 303 validation Standard
②. Add jar package for Hibernate validator Validation Framework
③. add <mvc:annotation-driven/> in the SPRINGMVC configuration file
④. need to add corresponding annotations on the Bean's properties
⑤. adding @Valid annotations before the target method bean type

Note: the Bean object that needs to be validated and its bound result object or Error object are paired, and they are not allowed to declare other entry parameters

1@RequestMapping (value= "/emp", method=Requestmethod.post)2      publicString Save (@Valid employee employee, Errors result,3map<string, object>Map) {4System.out.println ("save:" +employee);5         6         if(result.geterrorcount () > 0){7System.out.println ("something went Wrong!"));8             9              for(fielderror error:result.getFieldErrors ()) {TenSystem.out.println (error.getfield () + ":" +error.getdefaultmessage ()); one             } a              -             //if validation is wrong, move to a custom page -Map.put ("departments", departmentdao.getdepartments ()); the             return"input"; -         } -          - Employeedao.save (employee); +         return"redirect:/emps"; -}
View CodeDisplay errors on the page

Spring MVC Saves the validation results of the Form/command object to the corresponding Bindingresult or Errors object, and saves all the validation results to the "hidden model"

All the data in the implied model will eventually be exposed to the JSP view object through the HttpServletRequest property list, so you can get the error message in the JSP
Error messages can be displayed via <form:errors path= "userName" > on JSP page

Birth: <form:input path= "Birth"/><form:errors path= "Birth" ></form:errors>
Internationalization of the prompt message

Each property generates a corresponding Fielderror object when data binding and data validation errors Occur.
When a property validation fails, the validation framework generates 4 message codes for the property, which are prefixed with the validation of the annotation class name , combined with modleattribute, property names, and property type names to generate multiple corresponding message codes: for example, in the User class The Password property standard has a @Pattern annotation that produces the following 4 error codes when the property value does not meet the rules defined by the @Pattern:
Pattern.user.password
Pattern.password
Pattern.java.lang.String
Pattern
When you use the Spring MVC tag to display an error message, spring MVC checks to see if the web context has a corresponding internationalized message, and if it does not, displays the default error message, otherwise internationalized messages are Used.

Example:

<!--configuring internationalized Resource Files--><bean id= "messagesource" class= " Org.springframework.context.support.ResourceBundleMessageSource "><property name=" basename "value=" i18n " ></property></bean>

An error message is created in the implied model if there is an error in data type conversion or data format conversion, or if the parameter does not exist or an error occurred while invoking the processing Method. The error code prefix is described below:
Required: the necessary parameters do not Exist. If a @RequiredParam ("param1") is marked with an entry parameter, but the parameter does not exist
Typemismatch: data type mismatch occurs during data binding –
Methodinvocation:spring MVC encountered an error while invoking the processing method

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.