只需编写您自己的转换器并扩展javax.faces.convert.DateTimeConverter
- 这样你就可以重用所有的属性<f:convertDateTime>
支持。它还将负责本地化。不幸的是,编写带有属性的转换器有点复杂。
创建组件
首先编写自己的转换器来扩展javax.faces.convert.DateTimeConverter
- 只需让超级调用完成所有工作(包括语言环境)并将结果从 LocalDate 转换为 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));
}
}
}
然后创建一个文件LocalDateConverter-taglib.xml
in META-INF
:
<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
:
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/META-INF/LocalDateConverter-taglib.xml</param-value>
</context-param>
Usage
要在 JSF 页面中使用新标签,请添加新标签库xmlns:ldc="http://example.com/LocalDateConverter"
并使用标签:
<ldc:convertLocalDate type="both" dateStyle="full"/>