簡體   English   中英

@FacesConverter(forClass = Clazz.class)和p:calendar

[英]@FacesConverter(forClass = Clazz.class) and p:calendar

基本的Joda時間轉換器(此線程的上下文中的代碼絕對是多余的):

@Named
@ApplicationScoped
@FacesConverter(forClass = DateTime.class)
public class DateTimeConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }

        try {
            return DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa Z").parseDateTime(value).withZone(DateTimeZone.UTC);
        } catch (IllegalArgumentException | UnsupportedOperationException e) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "Message"), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null) {
            return "";
        }

        if (!(value instanceof DateTime)) {
            throw new ConverterException("Error");
        }

        try {
            return DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa Z").print(((DateTime) value).withZone(DateTimeZone.forID("zoneId")));
        } catch (IllegalArgumentException e) {
            throw new ConverterException("Error", e); // Not required.
        }
    }
}

為何/ <p:calendar>不能使用它,除非/直到使用converter屬性明確指定它為止?

<p:calendar converter="#{dateTimeConverter}" value="{bean.dateTimeValue}" .../>

與其他組件一樣,由於轉換器使用了修飾符,因此無需提及converter屬性就可以正常工作

@FacesConverter(forClass = DateTime.class)

<p:calendar>不支持此功能嗎?

使用PrimeFaces 5.2和JSF 2.2.12。

基於5.2的CalendarRenderer#encodeEnd() ,它使用CalendarUtils#getValueAsString()獲取輸出值。 如果確實有按類的轉換器,它的確不會通過Application#createConverter(Class)進行查詢。

51          //first ask the converter
52          if(calendar.getConverter() != null) {
53              return calendar.getConverter().getAsString(context, calendar, value);
54          }
55          //Use built-in converter
56          else {
57              SimpleDateFormat dateFormat = new SimpleDateFormat(calendar.calculatePattern(), calendar.calculateLocale(context));
58              dateFormat.setTimeZone(calendar.calculateTimeZone());
59              
60              return dateFormat.format(value);
61          }

這證實了您觀察到的行為。 您最好向PrimeFaces家伙創建一個問題報告,要求在適當的位置添加一個dateof instanceof Date ,在相反的情況下,請從應用程序中按類獲取轉換器,如下所示:

Converter converter = context.getApplication().createConverter(value.getClass());
if (converter != null) {
    return converter.getAsString(context, calendar, value);
}
else {
    throw new IllegalArgumentException(value.getClass());
}                    

考慮到Java8的java.time API的使用越來越多,這確實是有道理的。 順便說一句,在CalendarRendererCalendarUtils中還有其他一些地方可以/應該實現這一點(它們實際在執行instanceof檢查,但不按類將其委托給轉換器,如果有的話)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM