6.6 Spring3 Field Formatting

Source: Internet
Author: User
Tags dateformat locale

6.6spring3Field Formatting

core.convert is a generic type conversion system. It provides a unified conversionserviceapi Converter SPI spring containers Use this system to bind bean spel databinder spel short strong turn to long to complete the expression.setvalue (Objectbean, Object value) core.convert system to perform this strong turn.

Now consider a typical customer environment (such as a web or desktop apps) for type conversion requirements. In such an environment, you need to convert the string to other types to support the customer backhaul process ( Translator Note: That is, the user passes the value of the server to the process ), and you need to turn it into a Span lang= "en-us" >string to support the page rendering process ( Translator Note: The process by which the server passes the value to the user ). In addition, you typically need to localize string values. The more general core.convert converter SPI does not directly support such formatting requirements. So in order to support it directly, spring3 presents a convenient formatterspi , which acts as The substitution of propertyeditors provides a simple and robust implementation for the customer environment.

in general, when you need to implement generic type conversion logic, use the Converter SPI , such as java.utils.Date and the Java.lang.Long when the types are converted to each other. When you are in a client environment, such as in a Web application, you need to parse the field values and output them in a localized format using formatterspi. the conversionservice provides a unified type conversion API for two SPI types.


Formatterspi

implements the field formatting logic. Formatter SPI simple and strongly-typed:

Package Org.springframework.format;public interface formatter<t> extends Printer<t>, parser<t> {}

Formatter inherited the printer and parser interface two building-block (components, very interesting words)

Public interface Printer<t> {String print (T object, locale locale);}

Import Java.text.parseexception;public interface Parser<t> {T parse (String clientvalue, locale locale) throws ParseException;}

To create your own formatter, just implement the formatter interface. The parameter T is the type of object that needs to be formatted, such as Java.util.Date. Implement the print () method to print an instance of a formatted and localized T locally on the customer. Implement the Parse () method to convert the formatted data of a client into an instance of T. If a parse operation fails, then your formatter should throw a parseexception or illegalargumentexception. Make sure your formatter implementation is thread-safe.

For convenience, some formatter implementations have been provided in the format sub-package. The number package provides a numberformatter,currencyformatter and a percentformatter, They use Java.text.NumberFormat to format the Java.lang.Number object. The datetime package provides a dateformatter that uses Java.text.DateFormat to format the Java.util.Date object. The Datetime.joda package provides a comprehensive datetime format support based on the Joda Time library.

Consider an example of a formatter implementation class--dateformatter

Package Org.springframework.format.datetime;public Final class Dateformatter implements formatter<date> { private string Pattern;public Dateformatter (string pattern) {This.pattern = pattern;} Public String print (date date, locale locale) {if (date = = null) {return "";} return GetDateFormat (locale). Format (date);} Public Date Parse (String formatted, locale locale) throws ParseException {if (formatted.length () = = 0) {return null;} return GetDateFormat (locale). Parse (formatted);} protected DateFormat GetDateFormat (locale locale) {DateFormat DateFormat = new SimpleDateFormat (this.pattern, locale); Dateformat.setlenient (false); return dateformat;}}

The spring team welcomes the contributions from the community to formatter. can be submitted by http://jira.springframework.org.


Annotation-driven formatting

As you'll see in a minute, field formatting can be configured by field type or annotation. In order to bind an annotation and a format, implement Annotationformatterfactory ( Translator Note: Associate A and this by a to make this factory printer and parser ):

Package Org.springframework.format;public Interface Annotationformatterfactory<a extends annotation> {Set< Class<?>> getfieldtypes (); Printer<?> GetPrinter (A annotation, class<?> fieldtype); Parser<?> Getparser (A annotation, class<?> fieldtype);}

Parameter A is the annotation type of the field to be associated with the formatted logic, such as Org.springframework.format.annotation.DateTimeFormat. The Getfieldtypes () method returns the type of field that may be used for annotations. The GetPrinter () method is used to return a printer to output the value of the annotated field. The Getparser () method is used to return a parser to parse a annotated field into the value that the client will display.

The following annotationformatterfactory binds the @numberformat annotation to a formatter. This annotation allows to define a digital style (style, translator note: such as currency, PERCENT) or a number format (pattern, translator Note: such as #,###):

Public final class Numberformatannotationformatterfactory implementsannotationformatterfactory<numberformat> {public set<class<?>> getfieldtypes () {return new hashset<class<?>> (Aslist (newclass<? >[] {short.class, Integer.class, Long.class, Float.class,double.class, Bigdecimal.class, BigInteger.class});} Public printer<number> GetPrinter (NumberFormat annotation,class<?> fieldtype) {return Configureformatterfrom (annotation, fieldtype);} Public parser<number> getparser (NumberFormat annotation,class<?> fieldtype) {return Configureformatterfrom (annotation, fieldtype);} Private formatter<number> Configureformatterfrom (numberformat annotation, class<?> fieldtype) {if (! Annotation.pattern (). IsEmpty ()) {return new Numberformatter (Annotation.pattern ());} else {Style style = Annotation.style (), if (style = = style.percent) {return new Percentformatter ();} else if (style = = style.currency) {return New Currencyformatter ();} else {RETurn new Numberformatter ();}}} 

To trigger formatting, simply add the @numberformat annotation to the field:

public class MyModel {@NumberFormat (style=style.currency) private BigDecimal decimal;}

Formatting Annotations API

The Org.springframework.format.annocation package contains a handy formatting annotation API. Use @numberformat to format the Java.lang.Number field. Use @datetimeformat to format the Java.util.date,java.util.calendar,java.util.long or Joda time field.

The following example uses @datetimeformat to format java.util.Date as an ISO date type (YYYY-MM-DD):

public class MyModel {@DateTimeFormat (iso=iso. Date) private date date;}

formatterregistry SPI

Formatterregistry is an SPI that registers formatters and converters. Formattingconversionservice is an implementation class for Formatterregistry and is suitable for most environments. This implementation class can use Formattingconversionservicefactorybean to programmatically or declaratively configure it as a spring bean. Since this implementation also implements Conversionservice, it can be configured directly and used with spring's DataBinder and Spel.

Here's a look at Formatterregistry SPI:

Package Org.springframework.format;public Interface Formatterregistry extends Converterregistry {void Addformatterforfieldtype (class<?> FieldType, printer<?> Printer, parser<?> Parser); void Addformatterforfieldtype (class<?> FieldType, formatter<?> Formatter); void Addformatterforfieldtype ( Formatter<?> Formatter); void Addformatterforannotation (annotationformatterfactory<?,? > Factory);}

As shown above, formatters can be registered by field type or annotation.

The formatterregistry SPI allows you to centrally configure formatting rules instead of repeating them in individual controllers. For example, you might want to format all date fields in a certain way, or a field with an annotation in a certain way. with a shared formatterregistry, once you have defined the rules, they can be applied to the formatting at any time.


Formatterregistrar SPI

Formatterregistrar is an SPI that is used to register formatters and converters through formatterregistry .

Package Org.springframework.format;public interface Formatterregistrar {void Registerformatters (formatterregistry registry);}

Formatterregistrar is useful when you need to register more than one related converters and fomatters for a specified formatting category, such as a date type format.


Configuring Formatting in spring MVC

In a spring MVC application, you can precisely configure a custom Conversionservice instance and use it as a property of the Annotation-driven element in an MVC namespace. This conversionservice can be used wherever the controller's data binding is needed for any type conversion. If Conversionservice is not configured accurately, then SPRINGMVC will automatically register a default formatters and converters, which can convert some common types, such as numbers and dates ( Translator Note: This is also required to configure the <mvc:annotation-driven> ).

To rely on the default formatting rules, do not add additional configuration to your spring MVC configuration XML file.

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Mvc= "Http://www.springframework.org/schema/mvc" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: Schemalocation= "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/ Spring-beans-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/ Spring-mvc-3.0.xsd "><mvc:annotation-driven/></beans>

With this line of configuration, the default formatters that are formatted for the numbers and date types are registered. Includes support for @numberformat and @datetimeformat annotations. Support for Joda time format Library is also available if Classpath has Joda TIME's jar package.

To inject a Conversionserivce instance that contains custom formatters and converters, we need to set the Conversion-service property (in the Annotation-driven of the MVC namespace), You then specify the custom converters in the Conversionservice instance, Formatters or Formatterregistrars as a property of Formattingconversionservicefactorybean:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Mvc= "Http://www.springframework.org/schema/mvc" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: Schemalocation= "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/ Spring-beans-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/ Spring-mvc-3.0.xsd "><mvc:annotation-driven conversion-service=" Conversionservice "/><bean id=" Conversionservice "class=" Org.springframework.format.support.FormattingConversionServiceFactoryBean ">< Property name= "Converters" ><set><bean class= "Org.example.MyConverter"/></set></property ><property name= "formatters" ><set><bean class= "Org.example.MyFormatter"/><bean class= " Org.example.MyAnnotationFormatterFactory "/></set></property><property name=" Formatterregistrars "><set><bean CLAss= "Org.example.MyFormatterRegistrar"/></set></property></bean></beans> 

Note: When you want to use Formatterregistrars, you can read the "FORMATTERREGISTRARSPI" section to get more information about Formattingconversionservicefactorybean.









6.6 Spring3 Field Formatting

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.