【问题标题】:Prevent localized date time from being submitted防止提交本地化日期时间
【发布时间】:2016-04-29 14:00:37
【问题描述】:

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> 组件本身提交或同一表单上的某些其他组件在转换/验证期间失败,在这种情况下,日历组件将预先填充本地化的日期时间除非手动将给定 <p:calendar> 中的本地化日期时间重置为默认语言环境,否则在所有后续尝试提交表单时将无法在 getAsObject() 中转换。

以下将通过第一次尝试提交表单,因为没有转换/验证违规。

但是,如果以下字段之一出现转换错误,

那么日历组件中的两个日期都将根据所选的语言环境 (hi_IN) 进行更改,因为其中一个字段存在转换错误,在随后的尝试中显然无法在 getAsObject() 中转换, 如果在通过为字段提供正确值来修复转换错误后尝试提交包含组件的表单。

有什么建议吗?

【问题讨论】:

    标签: jsf converter locale


    【解决方案1】:

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

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

    为了使用组件特定的语言环境,它必须作为组件属性提供。这是一个示例,前提是faces-config.xml 中的<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

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多