I have read about component binding with binding
attribute in following questions:
I understand that it binds the UI component behind the JSF tag in the view to an UIComponent
property in the backing bean. However, I am confused what the use of component binding is and when we should use it. Can someone explain it in a more simpler way and give some practical examples?
If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument. In effects, it binds a reference of the component instance in the component tree to a scoped variable.
To bind a component's value to a managed bean property, a component tag's value attribute uses an EL value expression. To bind a component instance to a bean property, a component tag's binding attribute uses a value expression.
You should use it if you want to have access to the entire UIComponent
instead of just only its value. For example, to access some methods which can't be invoked/bound in the view. This is answered in the 1st question you found: JSF component binding - some confusion
The 2nd question which you found, component binding vs findComponent() - when to use which?, merely answers "binding
versus findComponent()
", it does not answer "binding
versus value
" at all as you seem to think. Please don't get confused by this. value
would obviously win over binding
.
In real world code, component binding to the backing bean is often only used whenever the developer needs to manipulate its children programmatically by e.g. component.getChildren().add(...)
. The bean should however be request scoped. A broader scope may lead to inconsitenties as component instances are basically created on a per-request basis and shouldn't be shared across multiple requests. The view scope can also, but this is very memory inefficient, and on Mojarra versions older than 2.1.18, partial state saving must also be turned off, otherwise the view scoped bean instance referenced by binding
will implicitly be recreated on every request. See also JSTL in JSF2 Facelets... makes sense? for a related answer.
It's also possible to bind the component to "the view". E.g.
<h:someComponent binding="#{some}">
This refers to an instance of UIComponent
in the Facelet scope ("page scope"). This enables you to use for example #{some.clientId}
, #{some.value}
elsewhere in the same page. Note that no backing bean is involved here. See also JSF component binding without bean property.
Here are some real world use appliances of binding
attribute:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With