I would like to get the i...">

How to get caller id in getter method?

In the following example:

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

I would like to get the id calling component foo in the getter method so that I can return the size from the properties file using the foo.length key.

 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?

+2
source share
2 answers

Because JSF 2.0 contains a new implicit EL variable in the component area: #{component} , which refers to the current instance of UIComponent . Among the methods for getting it is getId() , which you need.

So you can just do:

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

from

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

Alternatively, you can also make variableConfig a @ApplicationScoped @ManagedBean so you can just do:

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

(using the fully qualified name of the method in EL instead of the property name, it is necessary when you want to pass arguments to the method, so just variableConfig.sizeFor(component.id) will not work or you must rename the actual getSizeFor() method to sizeFor() in the class)

+3
source

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

If you are using 1.x, you can try the EL function, which places the component identifier in the request area under some name that your bean support method can get.

eg.

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

The implementation of the EL method may 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 bean configuration getSize () method is called, the identifier of the calling component will be available through "callerID" in the request area. To make it a little neater, you must add a finally block to remove the variable from the scope after the call. (note that I have not tried the above code, but hopefully demonstrates this idea)

Again, this will be the last resort when you are at JSF 1.x. The cleanest solution uses JSF 2.0 and describes the BalusC method.

+1
source

All Articles