如果您想使用单个模型值,则这种特殊情况是不可能的。
然而,这是复合组件的完美候选者。它允许您将单个模型值绑定到一组密切相关的现有组件,并在支持组件中执行处理/转换,与视图和支持 bean 完全分离。可以在本文中找到其中一个示例:具有多个输入字段的复合组件。此示例可以针对您的具体情况进行如下更改:
/resources/components/inputTime.xhtml
:
<ui:component
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
>
<cc:interface componentType="inputTime">
<cc:attribute name="value" type="java.util.Date" shortDescription="The selected time. Defaults to now." />
</cc:interface>
<cc:implementation>
<span id="#{cc.clientId}" style="white-space:nowrap">
<h:inputText id="hour" binding="#{cc.hour}" maxlength="2" converter="javax.faces.Integer" />h
<h:inputText id="minute" binding="#{cc.minute}" maxlength="2" converter="javax.faces.Integer" />
</span>
</cc:implementation>
</ui:component>
com.example.InputTime
@FacesComponent("inputTime")
public class InputTime extends UIInput implements NamingContainer {
private UIInput hour;
private UIInput minute;
/**
* As required by <cc:interface>.
*/
@Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
/**
* Set initial hour and minute based on model.
*/
@Override
public void encodeBegin(FacesContext context) throws IOException {
Calendar calendar = Calendar.getInstance();
Date date = (Date) getValue();
if (date != null) {
calendar.setTime(date);
}
hour.setValue(calendar.get(Calendar.HOUR_OF_DAY));
minute.setValue(calendar.get(Calendar.MINUTE));
super.encodeBegin(context);
}
/**
* Returns the submitted value in HH-mm format.
*/
@Override
public Object getSubmittedValue() {
return hour.getSubmittedValue() + "-" + minute.getSubmittedValue();
}
/**
* Converts the submitted value to concrete {@link Date} instance.
*/
@Override
protected Object getConvertedValue(FacesContext context, Object submittedValue) {
try {
return new SimpleDateFormat("HH-mm").parse((String) submittedValue);
}
catch (ParseException e) {
throw new ConverterException(e);
}
}
public UIInput getHour() {
return hour;
}
public void setHour(UIInput hour) {
this.hour = hour;
}
public UIInput getMinute() {
return minute;
}
public void setMinute(UIInput minute) {
this.minute = minute;
}
}
用法:
<html ... xmlns:my="http://java.sun.com/jsf/composite/components">
...
<my:inputTime value="#{bean.date}" />
也可以看看: