基本轉換器(僅爲原型)在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()
,如果在通過提供程序修復轉換錯誤後試圖提交持有組件的表單確保該領域具有正確的價值。
有什麼建議嗎?