日历dateSelect事件不会使用LocalDateTime触发侦听器

时间:2017-07-07 07:17:24

标签: ajax jsf primefaces calendar jsf-2.2

日历事件在选择新日期后不会触发show()方法,但是当我将dateBegin从LocalDateTime更改为java.util.Date时,我工作了。

环境:

  • JSF 2.2
  • Primefaces 6.1
  • Mojarra 2.2.13

calendar.xhtml

<p:calendar id="calDate" stepHour="24"
            value="#{Bean.dateBegin}"
            pattern="dd/MM/yyyy"
            converter="localDateTimeConverter">
   <p:ajax event="dateSelect" listener="#{Bean.show}"
            update="frmHi:tabView:tblHello"/>
</p:calendar>

Bean.java

private LocalDateTime dateBegin;    

public void show(SelectEvent event){
    Date data = (Date) event.getObject();
    if (data == null) {
        System.out.println("null");
    }
    else {
        System.out.println("not null");
    }
}
//getters and setters omitted

LocalDateTimeConverter.java

@FacesConverter("localDateTimeConverter")
public class LocalDateTimeConverter implements Converter {

    private static final String DATETIME_FORMAT = "dd/MM/yyyy HH:mm";

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }
        try {
            return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(DATETIME_FORMAT));
        } catch(DateTimeParseException e){
            throw new ConverterException(new FacesMessage(value + " is not a valid local date time"));
        }

    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof LocalDateTime) {
            return ((LocalDateTime) value).format(DateTimeFormatter.ofPattern(getPattern(component)));
        } else {
            throw new ConverterException(new FacesMessage(value + " is not a valid LocalDateTime"));
        }
    }

    private String getPattern(UIComponent component) {
        String pattern = (String) component.getAttributes().get("pattern");

        if (pattern == null) {
            return DATETIME_FORMAT;
        }

        return pattern;
    }

    private Locale getLocale(FacesContext context, UIComponent component) {
        Object locale = component.getAttributes().get("locale");
        return (locale instanceof Locale) ? (Locale) locale
            : (locale instanceof String) ? new Locale((String) locale)
            : context.getViewRoot().getLocale();
    }

    private ZoneId getZoneId(UIComponent component) {
        Object timeZone = component.getAttributes().get("timeZone");
        return (timeZone instanceof TimeZone) ? ((TimeZone) timeZone).toZoneId()
            : (timeZone instanceof String) ? ZoneId.of((String) timeZone)
            : null;
    }
}

0 个答案:

没有答案