如何将Wicket 7与Java 8中的java.time一起使用?

我有很多bean,都使用LocalDate和LocalDateTime。 Wicket中的DateTextField和所有其他小部件(如DatePicker)仅适用于java.util.Date。 有没有办法转换器注入Wicket 7,以便它使用LocalDate或LocalDateTime?

豆子看起来像这样:

public class SomeBean { Long id = null; LocalDate since = null; // plus getters and setters } 

Wicket表单当前使用CompoundPropertyModel

 CompoundPropertyModel model = new CompundPropertyModel( bean ); 

您可以将您的LocalDate等模型包装在IModel ,例如

 public static class LocalDateModel implements IModel { private IModel localDateModel; public LocalDateModel(IModel localDateModel){ this.localDateModel = localDateModel; } @Override public Date getObject() { return convertLocalDateToUtilDateSomehow(localDateModel.getObject()); } @Override public void setObject(Date object) { localDateModel.setObject(convertUtilDateToLocalDateSomehow(object)); } @Override public void detach() { localDateModel.detach(); } } 

如果您随后将这样的模型提供给您想要使用的表单组件,它应该可以正常工作。

如果您希望CompoundPropertyModel自动提供此类包装模型,则需要对其进行扩展并覆盖它的CompoundPropertyModel#wrapOnInheritance(Component component)方法,以推断需要包装模型。 就像是

 @Override public  IWrapModel wrapOnInheritance(Component component) { IWrapModel actualModel = super.wrapOnInheritance(component); if (actualModel.getObject() instanceOf LocalDate) { return new LocalDateModelButAlsoWrapping(actualModel); } else { return actualModel; } } 

其中LocalDateModelButAlsoWrapping不仅仅是上面的LocalDateModel示例的扩展,但它也实现了IWrapModel

如果使用此扩展而不是常规的CompoundPropertyModel ,它将检测字段何时为LocalDate并为组件(如DateTextField )提供模型,这些组件被包装成看起来像java.util.Date模型。

我给你的代码片段相当脏(你可能不应该让模型对象推断它的类型),因为我只提供它来说明一般机制,所以我建议你设计自己的方式来推断对象的类型期望(例如,您可以检查Component参数是否是DateTextField ),但这是我能想象的解决方案的一般方向。

您可以注册自己的转换器:

https://ci.apache.org/projects/wicket/guide/7.x/guide/forms2.html#forms2_3

 @Override protected IConverterLocator newConverterLocator() { ConverterLocator defaultLocator = new ConverterLocator(); defaultLocator.set(Pattern.class, new RegExpPatternConverter()); return defaultLocator; } 

相关: https : //issues.apache.org/jira/browse/WICKET-6200

你可以简单地从Wicket 8向后移植转换器类。你会发现这些附加到这个提交: https : //issues.apache.org/jira/browse/WICKET-6200 (AbstractJavaTimeConverter和你需要的LocalDate,LocalDateTime, LocalTime等)

当然,这对DateTextField没有帮助,因为它具有硬编码的Date类型参数。 为此,您可以使用上述转换器创建自己的子类,也可以使用常规Label和TextField,并在全局注册转换器,如下所示:

 @Override protected IConverterLocator newConverterLocator() { ConverterLocator converterLocator = new ConverterLocator(); converterLocator.set(LocalDateTime.class, new LocalDateTimeConverter()); converterLocator.set(LocalDate.class, new LocalDateConverter()); converterLocator.set(LocalTime.class, new LocalDateConverter()); return converterLocator; }