Play Framework 2.0: Custom Formats

I am trying to write my own formatted one (for DateTime fields, as opposed to java.util.Date fields), but it's hard for me to get this to work. I created my annotation and also extended the AnnotationFormatter class. I call play.data.format.Formatters.register (DateTime.class, the new MyDateTimeAnnotationFormatter ()) when the application loads, but the parsing and printing methods never start.

How am I supposed to do this?

Edit: this code may be useful;)

Annotation class (strongly inspired by the annotation class included in the Play Framework):

@Target({ FIELD }) @Retention(RUNTIME) @play.data.Form.Display(name = "format.datetime", attributes = { "pattern" }) public static @interface JodaDateTime { String pattern(); } 

Custom formatting class:

 public static class AnnotationDateTimeFormatter extends AnnotationFormatter<JodaDateTime, DateTime> { @Override public DateTime parse(JodaDateTime annotation, String text, Locale locale) throws ParseException { if (text == null || text.trim().isEmpty()) { return null; } return DateTimeFormat.forPattern(annotation.pattern()).withLocale(locale).parseDateTime(text); } @Override public String print(JodaDateTime annotation, DateTime value, Locale locale) { if (value == null) { return null; } return value.toString(annotation.pattern(), locale); } 

To register the formatter with the framework, I make this call in the static initializer of the Application class (maybe this would be better if you want to tell where):

 play.data.format.Formatters.register(DateTime.class, new AnnotationDateTimeFormatter()); 

I confirmed with a single click on the debugger that this call was created and that no errors were thrown, but still the formatter did not start, despite annotating the DateTime fields accordingly:

 @Formats.JodaDateTime(pattern = "dd.MM.yyyy HH:mm:ss") public DateTime timeOfRequest = new DateTime(); 

I'm at a loss here.

+6
source share
2 answers

You need to register for JodaDateTime instead of DateTime.

 play.data.format.Formatters.register(JodaDateTime.class, new AnnotationDateTimeFormatter()); 
0
source

I had a similar formatting issue for DateTime . I registered the formatter from my Global.onStart , as described here . It seems that just creating the Global class did not cause a reboot. As soon as I changed another file that caused a reboot (shown as --- (RELOAD) --- on the console output), it started working. Stopping and restarting the application should have the same effect.

0
source

Source: https://habr.com/ru/post/917563/


All Articles