[英]Composite JSF component with converter
我有一个复合JSF组件TimePicker.xhtml
与一个支持组件timePickerComponent
,使用如下:
<mi:timePicker style="display: initial;"
widgetVar="toTimepickerWidget"
converter="#{timePickerConverter}"
value="#{calendarBean.event.to}"
/>
并且timePickerConverter
以通常的方式创建:
public class TimePickerConverter implements Converter, Serializable {
@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
throws ConverterException {
// TODO Auto-generated method stub
return null;
}
}
如何在复合组件中使用此转换器?
更新:
这是复合组件的代码:
<cc:implementation componentType="timePickerComponent">
<h:outputScript name="js/timepicker/timepicker_helper.js" target="head"/>
<div id="#{cc.clientId}" style="#{cc.attrs.style}">
<p:inputText id="timepicker"
scrollHeight="200"
value="#{cc.timeLocal}"
size="5"/>
</div>
</cc:implementation>
基本上我想要的是将纯文本从inputText
转换为Date
对象。 日期的部分与我无关,我只需要Time的一部分。 顺便说一下,作为临时解决方案,我将使用本文所述的带有多个输入字段的 BalusC Composite组件的 getConvertedValue
但是想知道如何将此功能委托给外部转换器,如本文所述
通常,不会覆盖此方法,并将所有内容委托给默认的JSF Converter机制
为了使用转换器,您可以在方法getConvertedValue
中的后台组件中显式调用转换器。 可以从组件的converter
属性中检索converter
:
@FacesComponent("timePickerComponent")
public class TimePickerComponent extends UIInput implements NamingContainer {
...
@Override
public Object getSubmittedValue() {
UIInput hourComp = (UIInput) findComponent("timepicker_hour");
UIInput minutesComp = (UIInput) findComponent("timepicker_minutes");
return hourComp.getSubmittedValue() + ":" + minutesComp.getSubmittedValue();
}
@Override
protected Object getConvertedValue(FacesContext context,
Object newSubmittedValue) throws ConverterException {
Converter converter = (Converter) getAttributes().get("converter");
if (converter != null) {
return converter.getAsObject(context, this, (String) newSubmittedValue);
} else {
return newSubmittedValue;
}
}
}
请参阅示例代码: https : //github.com/destin/SO-answers/tree/master/SO-composite-jsf-component-with-converter
但是,此方法的缺点是JSF组件从String转换。 据我所知,你的组件包含很少的子元素。 他们所有的值都需要转换为字符串(就像我做的那样: hourComp.getSubmittedValue() + ":" + minutesComp.getSubmittedValue()
)。
因此,如果TimeConverters独立于JSF组件,您可能更愿意定义自己的层次结构。 这样的转换器将能够使用少量参数或一些复杂对象(如Time
)作为源。 这样的转换器可以用与我完全相同的方式检索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.