只需编写您自己的转换器并扩展javax.faces.convert.DateTimeConverter - 这样您就可以重用<f:convertDateTime> 支持的所有属性。它也将处理本地化。不幸的是,写一个带有属性的转换器有点复杂。
创建组件
首先编写您自己的扩展 javax.faces.convert.DateTimeConverter 的转换器 - 只需让超级调用完成所有工作(包括 locale-stuff)并将结果从/转换为 LocalDate。
@FacesConverter(value = LocalDateConverter.ID)
public class LocalDateConverter extends DateTimeConverter {
public static final String ID = "com.example.LocalDateConverter";
@Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
Object o = super.getAsObject(facesContext, uiComponent, value);
if (o == null) {
return null;
}
if (o instanceof Date) {
Instant instant = Instant.ofEpochMilli(((Date) o).getTime());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
} else {
throw new IllegalArgumentException(String.format("value=%s could not be converted to a LocalDate, result super.getAsObject=%s", value, o));
}
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
if (value == null) {
return super.getAsString(facesContext, uiComponent,value);
}
if (value instanceof LocalDate) {
LocalDate lDate = (LocalDate) value;
Instant instant = lDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
return super.getAsString(facesContext, uiComponent, date);
} else {
throw new IllegalArgumentException(String.format("value=%s is not a instanceof LocalDate", value));
}
}
}
然后在META-INF中创建一个文件LocalDateConverter-taglib.xml:
<facelet-taglib version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facelettaglibrary_2_2.xsd">
<namespace>http://example.com/LocalDateConverter</namespace>
<tag>
<tag-name>convertLocalDate</tag-name>
<converter>
<converter-id>com.example.LocalDateConverter</converter-id>
</converter>
</tag>
</facelet-taglib>
最后,在web.xml注册taglib:
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/META-INF/LocalDateConverter-taglib.xml</param-value>
</context-param>
用法
要在 JSF 页面中使用新标签,请添加新标签库 xmlns:ldc="http://example.com/LocalDateConverter" 并使用标签:
<ldc:convertLocalDate type="both" dateStyle="full"/>