What is component binding in JSF? When it is preferred to be used? [duplicate]
Solution 1:
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:
- disabling second text field after data validation through ajax of first text field
- Check which form has an error
- Input text validation based on drop-down list selection
- How to let validation depend on the pressed button?
- How to implement row numbering into h:dataTable
- Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime
Solution 2:
read this answer:
What is the advantages of using binding attribute in JSF?
However, a lot of people in the community do not recommend binding. See this article for example:
http://drewdev.blogspot.com/2009/01/jsf-component-binding-stinks.html