[英]Play Framework 2.0: Custom formatters
我正在嘗試編寫一個自定義格式化程序(對於DateTime字段,而不是java.util.Date字段),但我很難讓它工作。 我已經創建了我的注釋,並擴展了AnnotationFormatter類。 我在Application load上調用了play.data.format.Formatters.register(DateTime.class,new MyDateTimeAnnotationFormatter()),但是解析和print方法永遠不會觸發。
我該怎么做?
編輯:有問題的代碼可能會有所幫助;)
注釋類(受Play Framework附帶的注釋類的啟發):
@Target({ FIELD })
@Retention(RUNTIME)
@play.data.Form.Display(name = "format.datetime", attributes = { "pattern" })
public static @interface JodaDateTime {
String pattern();
}
自定義格式化程序類:
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);
}
要在框架中注冊格式化程序,我在Application類的靜態initalizer中進行此調用(可能有一個更好的地方放置它,隨時告訴我在哪里):
play.data.format.Formatters.register(DateTime.class, new AnnotationDateTimeFormatter());
我已經通過調試器單步執行確認此調用已經完成並且沒有拋出任何錯誤,但是仍然運行格式化程序,盡管如此適當地注釋DateTime字段:
@Formats.JodaDateTime(pattern = "dd.MM.yyyy HH:mm:ss")
public DateTime timeOfRequest = new DateTime();
我在這里失落。
您需要注冊JodaDateTime而不是DateTime。
play.data.format.Formatters.register(JodaDateTime.class, new AnnotationDateTimeFormatter());
我對DateTime
的格式化程序有類似的問題。 我是從我的注冊格式化Global.onStart
描述這里 。 看起來簡單地創建Global
類並沒有觸發重新加載。 一旦我修改了另一個觸發重載的文件--- (RELOAD) ---
在控制台輸出中顯示為--- (RELOAD) ---
)它就開始工作了。 停止並重新啟動您的應用應具有相同的效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.