2016-01-22 49 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