2010-12-17 48 views
2

考慮下面的例子:如何在getter方法中獲取調用組件的ID?

<h:inputText id="foo" size="#{configBean.size}" /> 

我想獲得調用組件fooid的getter方法,這樣我可以返回的大小從屬性由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; 
} 

我該如何做到這一點?

回答

3

由於JSF 2.0,組件範圍內有一個新的隱式EL變量:#{component}它引用當前的UIComponent實例。在它的getter方法中,有一個你需要的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)}" /> 

(使用完整的方法na我在EL而不是屬性名稱是必要的,只要你想傳遞參數的方法,所以才variableConfig.sizeFor(component.id)將無法​​正常工作,或者你必須在課堂上的實際getSizeFor()方法重命名爲sizeFor()

+0

哇!非常感謝 ! – bertie 2010-12-20 04:30:40

1

我覺得回答BalusC給出的是最好的答案。它顯示了JSF 2.0比1.x有如此巨大的改進的許多小原因之一。

如果您使用的是1.x版本,您可以嘗試一個EL函數,該函數將組件的ID放入請求範圍中,您的支持bean方法可以採用某種名稱。

E.g.

<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描述的方法。

+0

OP將問題標記爲'[jsf-2.0]',所以他使用JSF 2.0 :) – BalusC 2010-12-19 12:41:41

+0

對!我忽略了這一點。我的錯。 – 2010-12-19 14:29:44

相關問題