如何在getter方法中获取调用组件的ID?

给出以下示例:
<h:inputText id="foo" size="#{configBean.size}" />
我想在getter方法中得到调用组件
foo
id
,这样我就可以通过
foo.length
的键从属性文件中返回大小。
public int getSize() {
    String componentId = "foo"; // Hardcoded, but I should be able to get the id somehow
    int size = variableConfig.getSizeFor(componentId);
    return size;
}
我怎样才能做到这一点?     
已邀请:
从JSF 2.0开始,组件范围内有一个新的隐式EL变量:
#{component}
,它指的是当前的
UIComponent
实例。在其吸气方法中,你需要一个
getId()
。 所以你可以这样做:
<h:inputText id="foo" size="#{configBean.getSize(component.id)}" />
public int getSize(String componentId) {
    return variableConfig.getSizeFor(componentId);
}
或者你也可以把
variableConfig
变成
@ApplicationScoped
@ManagedBean
,这样你就可以做到:
<h:inputText id="foo" size="#{variableConfig.getSizeFor(component.id)}" />
(只要你想将参数传递给方法,就必须使用EL中的完整方法名而不是属性名,所以只有
variableConfig.sizeFor(component.id)
不起作用,或者你必须将实际的
getSizeFor()
方法重命名为
sizeFor()
)     
我认为BalusC给出的答案是最好的答案。它显示了为什么JSF 2.0比1.x有如此大的改进的众多小原因之一。 如果你在1.x上,你可以尝试一个EL函数,它将组件的ID放在请求范围内,以你的支持bean方法可以获取的某个名称。 例如。
<h:inputText id="foo" size="#{my:getWithID(configBean.size, 'foo')}" />
EL方法的实现可能如下所示:
public static Object getWithID(String valueTarget, id) {
    FacesContext context = FacesContext.getCurrentInstance();
    ELContext elContext = context.getELContext();

    context.getExternalContext().getRequestMap().put("callerID", id);

    ValueExpression valueExpression = context.getApplication()
        .getExpressionFactory()
        .createValueExpression(elContext, "#{"+valueTarget+"}", Object.class);

    return valueExpression.getValue(elContext);
 }
在这种情况下,每当调用配置bean的getSize()方法时,调用组件的ID将通过请求范围中的“callerID”获得。为了使它更整洁,你应该添加一个finally块,以便在调用完成后从范围中删除变量。 (请注意,我没有尝试上面的代码,但希望能够证明这个想法) 再次,当你使用JSF 1.x时,这将是最后的手段。最干净的解决方案是使用JSF 2.0和BalusC描述的方法。     

要回复问题请先登录注册