How to get ID of calling component in the getter m

2019-02-27 11:41发布

Given the following example:

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

I would like to get the id of the calling component foo in the getter method so that I can return the size from a properties file by a key of 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;
}

How can I achieve this?

标签: java jsf jsf-2 el
2条回答
姐就是有狂的资本
2楼-- · 2019-02-27 12:05

I think the answer BalusC gave is the best possible answer. It shows one of the many small reasons why JSF 2.0 is such a big improvement over 1.x.

If you're on 1.x, you could try an EL function that puts the ID of the component into the request scope under some name your backing bean method can pick up.

E.g.

<h:inputText id="foo" size="#{my:getWithID(configBean.size, 'foo')}" />

The EL method's implementation could look something like this:

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);
 }

In this case, whenever the getSize() method of the config bean is called, the ID of the calling component would be available via "callerID" in the request scope. To make it a little neater you should maybe add a finally block to remove the variable from the scope after the call has been made. (note that I didn't try the above code, but it hopefully demonstrates the idea)

Again, this would be a last resort when you're on JSF 1.x. The cleanest solution is using JSF 2.0 and the method BalusC describes.

查看更多
beautiful°
3楼-- · 2019-02-27 12:10

Since JSF 2.0, there's a new implicit EL variable in the component scope: #{component} which refers to the current UIComponent instance. Among its getter methods there's a getId() which you need.

So you can just do:

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

with

public int getSize(String componentId) {
    return variableConfig.getSizeFor(componentId);
}

Alternatively you can also make the variableConfig an @ApplicationScoped @ManagedBean so that you can just do:

<h:inputText id="foo" size="#{variableConfig.getSizeFor(component.id)}" />

(using the full method name in EL instead of the property name is necessary whenever you want to pass arguments to the method, so just variableConfig.sizeFor(component.id) won't work, or you must rename the actual getSizeFor() method to sizeFor() in the class)

查看更多
登录 后发表回答