我正在使用REST Web服务,并在视图中直接使用JAXB对象。像这样的XMLGregorianCalendar日期是这样的:

@XmlAttribute(name = "record")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar record;


尝试使用标准转换器时

<h:outputText value="#{bean.value.record}" >
  <f:convertDateTime pattern="dd.MM.yy" />
</h:outputText>


我在JSF2环境(JBoss-7.1.1-Final)中收到错误消息(翻译成英文)

javax.faces.convert.ConverterException: fSelection:dtSelection:0:j_idt42:
Converting of '2012-07-25T20:15:00' into string not possible.


似乎默认转换器不支持XMLGregorianCalendar类型。我想知道是否有这种日期类型的JSF转换器可用,因为这种要求似乎并不稀奇。

Edit Ravi提供了一个自定义转换器的功能示例,但这似乎不太灵活:


模式是硬编码的
不支持本地用户

最佳答案

该值应为java.util.Date类型。

因此,像这样从XMLGregorianCalendar获取Date对象:

record.toGregorianCalendar().getTime();


更新:

您可以这样使用:

<h:outputText value="#{bean.value.record.toGregorianCalendar().time}" >
    <f:convertDateTime pattern="dd.MM.yy" />
</h:outputText>


这实际上应该可以工作,但是由于您说您收到了IllegalAccessException,因此我不确定确切的原因。

或者,您也可以根据需要编写自己的转换器,该转换器将如下所示:

而且,如果要使用与dateTimeConverter相同的属性,则需要将它们作为属性传递给组件,并像这样扩展DateTimeConverter:

@FacesConverter("com.examples.Date")
public class XMLGregorianCalConverter extends DateTimeConverter {
 private static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getTimeZone("GMT");
 private String dateStyle = "default";
 private Locale locale = null;
 private String pattern = null;
 private String timeStyle = "default";
 private TimeZone timeZone = DEFAULT_TIME_ZONE;
 private String type = "date";

@Override
public Object getAsObject(FacesContext context, UIComponent component, String newValue) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    Map<String, Object> attributes = component.getAttributes();
    if(attributes.containsKey("pattern")){
        pattern = (String) attributes.get("pattern");
    }
    setPattern(pattern);
    if(attributes.containsKey("locale")){
        locale = (Locale) attributes.get("locale");
    }
    setLocale(locale);
    if(attributes.containsKey("timeZone")){
        timeZone = (TimeZone) attributes.get("timeZone");
    }
    setTimeZone(timeZone);
    if(attributes.containsKey("dateStyle")){
        dateStyle = (String) attributes.get("dateStyle");
    }
    setDateStyle(dateStyle);
    if(attributes.containsKey("timeStyle")){
        timeStyle = (String) attributes.get("timeStyle");
    }
    setTimeStyle(timeStyle);
    if(attributes.containsKey("type")){
        type = (String) attributes.get("type");
    }
    setType(type);

    XMLGregorianCalendar xmlGregCal = (XMLGregorianCalendar) value;
    Date date = xmlGregCal.toGregorianCalendar().getTime();
    return super.getAsString(context, component, date);
}

}


并在您的页面上这样使用:

<h:outputText value="#{bean.value.record}" >
    <f:converter converterId="com.examples.Date" />
    <f:attribute name="pattern" value="dd.MM.yy" />
</h:outputText>


受此问题启发/复制的代码:JSF convertDateTime with timezone in datatable

09-12 18:53