基本转换器(仅为原型)在String
和java.time.LocalDateTime
之间来回转换。防止提交本地日期时间
@FacesConverter("localDateTimeConverter")
public class LocalDateTimeConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(submittedValue, DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
} catch (IllegalArgumentException | DateTimeException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "Message"), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (!(modelValue instanceof LocalDateTime)) {
throw new ConverterException("Message");
}
Locale locale = context.getViewRoot().getLocale();
return DateTimeFormatter.ofPattern(pattern, locale).withZone(ZoneId).format(ZonedDateTime.of((LocalDateTime) modelValue, ZoneOffset.UTC));
}
}
要提交给数据库的日期时间应基于Locale.ENGLISH
。因此,它在getAsObject()
中是恒定的/静态的。
要从数据库检索的即将呈现给最终用户的日期时间基于用户选择的选定区域。因此,Locale
在getAsString()
中是动态的。
日期时间使用未被本地化以避免麻烦的<p:calendar>
来提交。
这将按预期工作,除非在转换/验证过程中提交本身或其它提交的表单上的其他组件的<p:calendar>
组件失败,这种情况下,日历组件将预先填充本地日期时间将无法在getAsObject()
的所有后续提交表单的尝试中转换失败,除非手动将给定的<p:calendar>
中的本地化日期时间重置为默认的区域设置。
由于没有转换/验证违规,下面将首先尝试提交表单。
然而如果有,在如下字段中的一个的转换错误,
然后无论是在日历组件的日期将根据所选择的语言环境而改变(hi_IN
),因为在其中一个字段中存在转换错误,在后续尝试中显然无法转换为getAsObject()
,如果在通过提供程序修复转换错误后试图提交持有组件的表单确保该领域具有正确的价值。
有什么建议吗?