Formatter in Spring3 with velocity formatted output instance

Source: Internet
Author: User

Before looking at this article, I hope you know something about the formatter mechanism of SPRING3, and you can poke at it without knowing it.

There are two levels of formatting in Spring3, one for type-level formatting and the other for field formatting.

First, for type-level formatting that is, for example, for the date type, I use a format scheme, which can be registered as follows:

Conversionservice.addformatter (New formatter<date> () {@Overridepublic String print (Date object, locale locale) { return null;} @Overridepublic Date Parse (String text, locale locale) throws parseexception {return null;}});

For field-level formatting, it is relatively flexible and is a scheme for formatting a field of a class (typically in annotated form):

public class Testentity {//@DateTimeFormat (pattern = "Yyyy-mm-dd HH:mm:ss") private date date; @NumberFormat (pattern = " RMB: ##.00 ") Private Double Salary;public Date getDate () {return date;} public void SetDate (date date) {this.date = date;} Public Double getsalary () {return salary;} public void Setsalary (Double salary) {this.salary = salary;}}


And for the parsing of the field is the same, if the field-level resolution, then when defining the method parameters, you need to bring the annotations:

@RequestMapping (value = "/FORMAT2") public String test2 (@NumberFormat @RequestParam ("salary") Double salary,     @ DateTimeFormat (pattern= "Yyyy-mm-dd HH:mm:ss") @RequestParam ("date") Date date) {    System.out.println (phonenumber );    SYSTEM.OUT.PRINTLN (date);    return "Format/success2";}

Given that the date type has a higher frequency of appearances in formatting, let's use date as an example: Let's first implement type-level formatting

public class Dateformatter implements formatter<date> {@Overridepublic String print (Date object, locale locale) {TR Y {return new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss", locale). Format (object);} catch (Exception e) {return new SimpleDate Format ("Yyyy-mm-dd", Locale). Format (object);}} @Overridepublic Date Parse (String text, locale locale) throws ParseException {try {return new SimpleDateFormat ("yyyy-mm-d D HH:mm:ss ", locale). Parse (text);} catch (Exception e) {return new SimpleDateFormat ("Yyyy-mm-dd", Locale). Parse (text);}}}

Here is also a magical application of try...catch, which we use to help us deal with the date types in two different formats

After writing the formatter, we'll register it in Formattingconversionservice.

Conversionservice.addformatter (New Dateformatter ());

In this way, we are using Conversionservice.converter (...). Method converts the date and string data, the parse and print methods in Dateformatter are called.

But it seems too much trouble to manually convert each time, spring seems to provide <spring:eval expression="Model.date"> To achieve automatic formatting, but this has not been touched

Or do it yourself, this is a combination of Velocity's directive to achieve it.

public class Formatterdirective extends Directive {private Formattingconversionservice conversionservice;@ Overridepublic String GetName () {return "formatter";} @Overridepublic int GetType () {return line;} @Overridepublic Boolean render (Internalcontextadapter context, Writer Writer,node Node) throws IOException, Resourcenotfoundexception,parseerrorexception, Methodinvocationexception {if (Conversionservice = = null) { Conversionservice = new Defaultformattingconversionservice (); Conversionservice.addformatter (new DateFormatter ()); String param = node.jjtgetchild (0). Value (context). ToString (); string[] params = param.split ("\ \"); Beanwrapper beanwrapper = new Beanwrapperimpl (Context.get (params[0]));//Get type information TypeDescriptor Descriptor;descriptor = Beanwrapper.getpropertytypedescriptor (Params[1]); TypeDescriptor stringdescriptor = typedescriptor.valueof (string.class), Object value = Conversionservice.convert ( Beanwrapper.getpropertyvalue (Params[1]), descriptor,stringdescriptor); Writer.write (Value.toSTring ()); return true;}} 

Front page wording:

#formatter ("person.salary") <br/> #formatter ("person.date") <br/>

Does it look similar to the one that spring offers?



Formatter in Spring3 with velocity formatted output instance

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.