代码之家  ›  专栏  ›  技术社区  ›  Tiny user825402

阻止提交本地化日期时间

  •  1
  • Tiny user825402  · 技术社区  · 10 年前

    基本转换器(仅为原型)在 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: 日历> 正在提交的组件本身或正在提交的同一表单上的某些其他组件在转换/验证过程中失败,在这种情况下,日历组件将预先填充本地化的日期时间,该日期时间将无法转换为 获取AsObject() 除非给定的本地化日期时间 <p: 日历> 手动重置为默认区域设置。

    由于没有转换/验证违规,下面将传递第一次提交表单的尝试。

    enter image description here

    然而,如果在如下字段之一中存在转换错误,

    enter image description here

    然后,日历组件中的两个日期都将根据所选区域设置进行更改( hi_IN ),因为其中一个字段存在转换错误,显然无法在 获取AsObject() 在随后的尝试中,如果在通过为字段提供正确的值来修复转换错误之后试图提交包含组件的表单。

    有什么建议吗?

    1 回复  |  直到 10 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    在转换器中 getAsString() 您正在使用视图的区域设置来格式化日期。

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

    为了使用特定于组件的语言环境,必须将其作为组件属性提供。以下是一个示例 <locale-config><default-locale> 在里面 faces-config.xml 设置为 en .

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

    在转换器中,您可以按如下方式提取它:

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

    同时,您的转换器的基本转换器示例已被修改,以适当考虑到这一点: How to use java.time.ZonedDateTime / LocalDateTime in p:calendar .

    推荐文章