2016-01-22 153 views
1

基本轉換器(僅爲原型)在Stringjava.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()中是恆定的/靜態的。

要從數據庫檢索的即將呈現給最終用戶的日期時間基於用戶選擇的選定區域。因此,LocalegetAsString()中是動態的。

日期時間使用未被本地化以避免麻煩的<p:calendar>來提交。

這將按預期工作,除非在轉換/驗證過程中提交本身或其它提交的表單上的其他組件的<p:calendar>組件失敗,這種情況下,日曆組件將預先填充本地日期時間將無法在getAsObject()的所有後續提交表單的嘗試中轉換失敗,除非手動將給定的<p:calendar>中的本地化日期時間重置爲默認的區域設置。

由於沒有轉換/驗證違規,下面將首先嚐試提交表單。

enter image description here

然而如果有,在如下字段中的一個的轉換錯誤,

enter image description here

然後無論是在日曆組件的日期將根據所選擇的語言環境而改變(hi_IN),因爲在其中一個字段中存在轉換錯誤,在後續嘗試中顯然無法轉換爲getAsObject(),如果在通過提供程序修復轉換錯誤後試圖提交持有組件的表單確保該領域具有正確的價值。

有什麼建議嗎?

回答

1

在轉換器的getAsString()中,您使用視圖的區域設置來格式化日期。

Locale locale = context.getViewRoot().getLocale(); 

爲了使用特定於組件的屬性,必須提供組件屬性。這裏有一個例子,假設中的<locale-config><default-locale>被設置爲en

<p:calendar ... locale="#{facesContext.application.defaultLocale}"> 

在轉換器可以提取它如下:

Locale locale = (Locale) component.getAttributes().get("locale"); 

您轉換器的基本轉換器例子在同時被改變妥善考慮到這一點:How to use java.time.ZonedDateTime/LocalDateTime in p:calendar