Spring MVC Data Transformation and formatting

Source: Internet
Author: User
Tags numeric

Spring MVC Data Binding

Spring MVC analyzes the signature of the target method through the reflection mechanism and binds the request message to the processing method into the parameter.

The core part of data binding is DataBinder.

The spring MVC main framework passes the ServletRequest object and the processing method into the Parameter object instance to the Databinder,databinder call the Conversionservice component that is assembled in the spring MVC context for data type conversions , the data is formatted, the message in ServletRequest is populated into the Parameter object, and then the validator component is called to validate the data legitimacy of the incoming parameter object that has the requested message data bound, and eventually the data-bound result Bindingresult object is generated. The bindingresult contains the incoming parameter object for the completed data binding, and also contains the appropriate checksum error object.

Data conversion

Conversionservice is the core interface of the spring type conversion system, In the Org.springframework.core.convert package, you can use Org.springframework.context.support.ConversionServiceFactoryBean to define a C in the spring context Onversionserivce. Spring automatically recognizes the Conversionservice in the context and uses it for data conversion in the case of bean attribute configuration and Springmvc processing method into the parameter binding.

<bean id= "Conversionserivce"

class= "Org.springframework.context.support.ConversionServiceFactoryBean"/>

The Factorybean creates Conversionserivce built-in converters that can register a custom type converter with the Convertors property of the Factorybean

<bean id= "Conversionserivce"

class= "Org.springframework.context.support.ConversionServiceFactoryBean" >

<propertyname= "Converters" >

<list>

<bean class= "xxxxx"/>

</list>

</property>

</bean>

Spring Built-in 3 type converter interface, respectively, is

Converter<s,t>

Converterfactory<s,r>

Genericconverter

A custom type converter must implement one of the

Converter

The converter interface is Spring's simplest converter interface and contains only one method

public interface converter<s,t>{

Tconverter (s source);//responsible for converting S-type objects to T-type objects

}

Converterfactory<s,r>

The Converterfactory interface is defined as follows

public interface converfactory<s,r>{

<T,R>Converter<S,T> Getconverter (class<t> targetType);

}

S is the source type, R is the base class for the target type, and T is the type that extends to the R base class. such as spring's stringtonumberconverfactory implements the Converterfactory interface, which encapsulates a string converted into a variety of data types converter

Using Conversionserivce in spring MVC

<userName>:<password>:<realName>-> User

1, <mvc:annotation-drivenconversion-service= "Conversionservice"/> Assembly custom Conversionservice

<mvc:annotation-driven> This tab simplifies SPRINGMVC related configuration, by default, It creates and registers a default defaultannotationhandlermapping and a annotationmethodhandleradapter, if a custom corresponding component exists in the context bean,spring MVC will automatically overwrite the default with a custom bean, in addition to the,<mvc:annotation-driven/> tag registering a default Conversionservice, That is, Formattingconversionservicefactorybean, because you want to customize the converter, you want to display a CONVERSIONSERIVCE overrides the default implementation.

2. Assembly of Custom Converters

<bean id= "Conversionserivce"

class= "Org.springframework.context.support.ConversionServiceFactoryBean" >

<propertyname= "Converters" >

<list>

<bean class= "Stringtouserconverter"/>

</list>

</property>

</bean>

3. Write Converter class

public class Stringtouserconverter implementsconverter<string,user>{

Publicuser convert (String source) {

Useruser = new User ();

if (source!=null) {

Stringitems = Source.split (":");

User.setusername (Items[0]);

User.setpassword (Items[1]);

User.setrealname (items[2]);

}

}

}

@InitBinder

To add a custom editor using @initbinder in the controller

@InitBinder

public void Initbinder (Webdatabinder binder) {

Binder.registercustomeditor (User.class,newusereditor ());

}

Spring MVC uses Webdatabinder to handle the binding of request messages and processing methods into parameters, and the custom editor must implement the PropertyEditor interface.

Global Scope Custom Editor

1. Implement Webbindinginitalizer interface

public void Initbinder (Webdatabinder binder,webrequestrequest);

2, in the web context through the Annotationmethodhandleradapter assembly

<bean class= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >

<propertyname= "Webbindinginitializer" >

<bean class= "xxx"/>

</property>

</bean>

Spring MVC looks for the type conversion editor in the following order

@InitBinder->conversionservice->webbindinginitializer

Data formatting

Spring uses the converter to convert the source type object to the target type object, and the spring converter does not provide the input and output information formatting work.

Annotation-driven formatting

Annotations Drive Important Interfaces

Spring provides a Org.springframework.format package with a

Annotationformatterfactory<a extends Annotation> interface, the interface method is as follows:

Set<class<?>> getfieldtypes (): Indicates which classes can annotate a annotation

Parser<?> Getparser (a annotation,class<?>fieldtype): Get a specific type of Parser according to note a

Printer<?> GetPrinter (aannotation,class<?> fieldtype): Get a specific type of Printer according to note a

Spring provides 2 built-in implementation classes that support annotation-driven formatting of arrays and numeric types, respectively

Numberformatannotationformatterfactorybean: Supports attribute usage for numeric types (@NumberFormat)

Jodadatetimeformatannotationformatfactorybean: for date type (@DateTimeFormat)

Enable the annotation-driven formatting feature

Spring defines a class formattingconversionservice that implements the Conversionserivce implementation, which extends to Genericconversionservice, which has both the type conversion function and the formatting function.

Formattingconversionservice also has a formattingconversionservicefactorybean, The latter is used to construct a formattingconversionserivce in the spring context, through which a custom converter can be registered, and custom annotation driver logic can be registered.

Numberformatannotationformatterfactorybean/jodadatetimeformatannotationformatfactory

is automatically registered to Formattingconversionservicefactorybean, so after assembling the Factorybean, it is possible to use the annotation-driven formatting feature in the input parameter bindings and model data output.

<bean id= "Conversionservice"

class= "Org.springframework.format.support.FormattingConversionServiceFactoryBean" >

<propertyname= "Converters" >

<list><bean class= "xxxx"/></list>

</property>

</bean>

Replace the original Conversionservicefactorybean with Formattingconversionservicefactorybean

The <mvc:annotation-driven/> tag creates the Formattingconversionservicefactorybean by default

@DateTimeFormat

You can annotate the Java.util.date,java.util.calendar,java.lang.long,joda time Type property

@DateTimeFormat (partten= "YYYY-MM-DD")

@NumberFormat to annotate numeric type properties

@NumberFormat (pattern= "#,###.##")

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.