Calling a method multiple times when using h:dataTable in JSF - jsf

Can you guys help me to explain the reason why the method is called multiple times when I used the h:dataTable in facelet page.
<h:dataTable id="listTable" styleClass="pageView_listForm"
value="#{ClassName.dataFactory(topic)}" border="2" rules="rows"
var="item" width="100%" cellpadding="1" cellspacing="0" rowClasses="panelRowOdd,panelRowEven" >
//Body
</h:dataTable>
Bean class
#ManagedBean (name="ClassName")
#SessionScoped
public class ClassName{
...
public DataModel <Person> dataFactory(String topic){
DataModel items = null;
..........
// This block code gets the list of Person
..........
return items;
}
}
I was launching the page when it called the method dataFactory multiple times. I did not know exactly what happen here? Is it a bug from JSF or my implementation.Can you guy help me?
Thank you.

when happens with Datatable, we should take care that such a method should not contain much business logic, Or Database interactions which are costly.
here i found some useful discussions....
Why JSF calls getters multiple times
Why is BackingBean method called multiple times when requesting facelet?
This
and here
Calling a method multiple times when using h:dataTable in JSF

Related

Jsf ui:repeat - method that populates the value is accessed even when submiting different form

In my actual project I have noticed that the method that populates the ui:repeat tag, is being invoked when there is a post call, even though the ui:repeat is not part of the submitted form.
I have been trying to check againts the jsf documentation if that is the way it should work, with no success.
Is it supposed to work this way?
Thanks in advance.
Sample code:
When the button is clicked the method anotherBean.getCollection is being invoked:
<h:form id="firstForm">
<h:commandButton action="#{someBean.someAction}"/>
</h:form>
<h:form id="secondForm">
<ui:repeat var="product" value="#{anotherBean.populatCollection}" >
<!-- CODE -->
</ui:repeat>
</h:form>
In first place, a getter method shouldn't be populating the value at all. A getter method should, as its name says, just return the already-populated value.
You're not terribly clear on the concrete functional requirement, i.e. when exactly did you intend to populate the value, but one way would be moving the populating logic to the #PostConstruct of #{anotherBean}.
#ManagedBean
#ViewScoped
public class AnotherBean {
private List<Something> getCollection; // Terrible variable name by the way.
#PostConstruct
public void init() {
getCollection = populateItSomehow();
}
public List<Something> getGetCollection() {
return getCollection; // See, just return the property, nothing more!
}
}
See also:
Why JSF calls getters multiple times
So, it looks like ui:repeat tag is invoking the methods assigned to its value argument when a post is done, no matter if the post is done from another form.
Thanks for the help.

JSF 2.0 dynamic form best practice

Update: for those flagging this to be closed as a duplicate, the supposed duplicate question is nothing like what I am asking. My problem is I do not know until render time what the question set will be, how many questions there will be or what the question types will be so I cannot use the technique described in the "possible duplicate" answer.
Part of our JSF 2.x application has a requirement to render sets of questions to the user where the questions and the question types are not known until run-time. e.g we have something like (getters/setters omitted for clarity) :
public class QuestionSet {
private List<Section> sections;
}
public class Section {
private String sectionTitle;
private List<Question> questions;
private SectionStatus status; // e.g. UNANSWERED, CURRENTLY_ANSWERING,ANSWERED, COMPLETED
}
public class Question {
private String questionText;
private QuestionType questionType; // E.G TEXT, RADIO, LIST, CHECKBOX
private List<String> options; // for RADIO/LIST/CHECKBOX types
private List<String> answers;
}
We need to render each section in a seperate div, depending on it's status (e.g. UNANSWERED would display a div with just the title, ANSWERED would display a div with the section title and a green tick mark, and CURRENTLY_ANSWERING would render a div with the section title and then each question with the appropriate input control based on the question type.
The questions are also dynamic during the run - e.g. if a user answers yes to a radio button question, this may prompt further sub-questions.
I am currently doing this using a binding, i.e.
<h:panelGroup binding = "#{bean.panelGroup}" />
and within the bean's getPanelGroup creating the component tree by hand usin things like HtmlPanelGroup, HtmlOutputText, UIInput with ValueExpressions etc. which works fine but on reading some of BalusC's answers, particlarly to this question: How does the 'binding' attribute work in JSF? When and how should it be used? I am wondering if there is a "better" approach?
One of the things that concerns me is that the getter is called during RECREATE_VIEW for reasons explained in the linked question (after invoking the method referred to in the binding) so unless I take steps to, in RECREATE_VIEW phase, just return the component I created in the last RENDER_RESPONSE phase, this introduces unnecessary expense of recreating something I've just created.
In this case, it also seems pointless that JSF calls my setter to set the thing I just gave it in the getter for the bound property. (my bean is View scope as I will need to use ajax for some of the functionality our users require)
Thoughts/opinions (Especially from the ever helpful BalusC) greatly appreciated...
I don't see much reason to use component binding in this case. You can decide in your view what to render and how. You can have <ui:fragment>/<c:if> to conditionally render elements basing on question type, <ui:repeat>/<c:forEach> to handle the question set, etc.
So, if I understand the workflow correctly, your question set will be determined in e.g. post constructor method:
#PostConstruct
public void init() {
questionSet = service.get();//get it somehow
}
Then you'll have a set of sections and each of these section will contain questions, or answers, and validity is to be checked via AJAX. If I understand you right, then you can have the following view:
<h:form id="q-set">
<ui:repeat value="#{bean.questionSet.sections}" var="section">
<div>#{section.title}</div>
<div class="#{section.status eq 'UNANSWERED' ? 'section-unanswered' : ... }"/>
<ui:fragment rendered="#{section.status eq 'ANSWERED' ?}"><div class="tick"/></ui:fragment> ...
<ui:fragment rendered="#{section.status eq 'ANSWERED' ?}">
<ui:repeat value="#{section.questions}" var="question">
<div>#{question.title}</div>
<ui:fragment rendered="#{question.type eq 'RADIO'}">
<h:selectOneRadio value="#{question.answers[0]}" validator="...">
<f:selectItems value="#{question.options}" var="opt" itemLabel="#{opt}" ... />
<f:ajax ...>
</h:selectOneRadio>
</ui:fragment>
...
</ui:repeat>
</ui:fragment>
</ui:repeat>
</h:form>
It looks like you are going to have too much logic/conditions in your view.
What about generating the view programmatically on the Java side ?
For tricky parts you may resort to JavaScript and JSON.

How to use component binding in JSF right ? (request-scoped component in session scoped bean)

Mojara 2.1.21
I've updated my question based on comments. I have two situation where a component is bound to server session bean. (Additional links with information: Binding attribute causes duplicate component ID found in the view and https://stackoverflow.com/a/12512672/2692917)
Version 1:
single.xhtml:
<h:outputText value=... binding="#{mysessionbean.out}" />
java:
#SessionScoped #Named public class Mysessionbean {
UIOutput out;
//getter and setter ....
}
Version 2:
template.xhtml:
<h:outputText value=... binding="#{mysessionbean.out}"
view1.xhtml:
<ui:composition template="template.xhtml" />
view2.xhtml:
<ui:composition template="template.xhtml" />
java:
#SessionScoped #Named public class Mysessionbean {
UIOutput out;
//getter and setter ....
}
Version 1 is ok. (At least I've not encounter any errors so far). But in version 2 the duplicate id error is occured if I navigate from one page to another. Why does it happen ?
Is it safe to use (request-scoped) component (in version 1) with session scoped binding ?
Are there another use cases to consider ?
Edit:
Functional requirement 1:
I want to use Primefaces datatable in a view. I need some info from this datatable. (Such as selected row or row index). So binding the datatable helps me to retrieve this info.
Functional requirement 2:
Components binding in composite components. They will be bound to session scoped bean. (And used mainly on one page, but what if I used it on another page ?
Requirements 3
The situation as in "Version 2". Template with primefaces menu and session scoped binding. For this I've used the EL-Binding.
In JSF 2.x, unless you want to manipulate components programmatically (which is at its own also rather fishy), there is no sensible real world use case to bind components to a backing bean. For sure not if they are further not been used in the backing bean itself, or if it are solely their attributes which are been flattened out.
As to the functional requirement of getting the current row of the data table, there are much better ways listed here, How can I pass selected row to commandLink inside dataTable?, for example if your environment supports EL 2.2:
<h:dataTable value="#{bean.items}" var="item">
<h:column>
<h:commandLink value="Foo" action="#{bean.foo(item)}" />
The two last requirements are totally unclear. At least, if you're doing something like:
<x:someComponent binding="#{bean.someComponent}" />
with in bean
someComponent.setSomeAttribute(someAttribute);
someComponent.setOtherAttribute(otherAttribute);
then you should instead be doing
<x:someComponent someAttribute="#{bean.someAttribute}" otherAttribute="#{bean.otherAttribute}" />
Or, if you intend to be able to use the component somewhere else in the view like so
<h:inputText ... required="#{not empty param[bean.save.clientId]}" />
...
<h:commandButton binding="#{bean.save}" ... />
and the instance is further nowhere been used in the bean, then just get rid of the unnecessary property altogether:
<h:inputText ... required="#{not empty param[save.clientId]}" />
...
<h:commandButton binding="#{save}" ... />
If there is really, really no way for some unclear reason, then split all request scoped properties of the session scoped bean out into a separate request scoped bean which you in turn bind to form actions. The session scoped one can just be injected as a #ManagedProperty of the request scoped one.
See also:
Binding attribute causes duplicate component ID found in the view
How does the 'binding' attribute work in JSF? When and how should it be used?
We ran into a similar problem and I just want to share our solution:
Problem:
In a view there was a (extended largely customized) datatable.
<x:dataTable binding="#{bean.someSomeDataTable}" />
After navigating to another page and back we wanted the datatable to have the exact same state. Previously we solved that by binding the datatable to to backing bean. This worked fine with JSPs. With Facelets we could not do that (Duplicate ID errors). So we used the binding, but only saved/restored the state of the datatable component.
public HtmlDataTable getSomeDataTable()
{
HtmlDataTable htmlDataTable = new HtmlDataTable();
if (tableState != null)
htmlDataTable.restoreState(FacesContext.getCurrentInstance(), tableState);
return htmlDataTable;
}
public void setSomeDataTable(HtmlDataTable table)
{
tableState = table.saveState(FacesContext.getCurrentInstance());
}

#ViewScoped, f:setPropertyActionListener only works once

I have 2 managedBeans: the first one (RequestScoped) sends a parameter to the second one (ViewScoped) through a h:commandLink. Both managedBeans are in the same page, but I use them in different tabs from a rich:TabPanel:
#ManagedBean
#RequestScoped
public class TheRequestScopedManagedBean {
private String number
...
#ManagedBean
#ViewScoped
public class TheViewScopedManagedBean {
private String number;
...
And here's the view, wich uses a rich:dataTable:
(The action method is only for showing the second tab from a rich:tabPanel).
// ... another dataTable's columns
<rich:column>
<f:facet name="header">Number</f:facet>
<b>
<a4j:commandLink value="#{theRequestScopedManagedBean.number}"
render="someRichPanel" action="#{anotherBean.showSecondTab}" immediate="true">
<f:setPropertyActionListener target="#{theViewScopedManagedBean.number}" value="#{theRequestScopedManagedBean.number}" />
</a4j:commandLink>
</b>
</rich:column>
The problem here is that theViewScopedBean shows the value only the first time, and when I try to pass it again, it shows its default value (null).
I've seen several questions on this website. But I really don't know what to do in this case.
action="#{anotherBean.showSecondTab}" is going to result in a navigation case firing. This will in turn result in the views and request scoped beans being destroyed and recreated (as is the expected behaviour for a view scoped bean).
If you're using EL2.2, you could easily just pass the value directly into a method in the view scoped bean. Let's assume your viewscoped bean has a method takeValue, you can pass the parameter directly into the method as in:
<a4j:commandLink value="#{theRequestScopedManagedBean.number}" render="someRichPanel" action="#{theViewScopedBean.takeValue(theRequestScopedManagedBean.number)}" immediate="true"/>
There are still cleaner ways to transmit data between pages.
Communication in JSF2.0

Primefaces commandButton: f:attribute does not work

Project uses Spring Webflow and JSF (PrimeFaces). I have a p:commandButton with f:attribute
<p:commandButton disabled="#{editGroupMode=='edit'}" action="edit_article_group" actionListener="#{articleGroupManager.setSelectedRow}" ajax="false" value="Edit">
<f:attribute name="selectedIndex" value="${rowIndex}" />
</p:commandButton>
Backend code (Spring injected bean):
#Service("articleGroupManager")
public class ArticleGroupManagerImpl implements ArticleGroupManager{
public void setSelectedRow(ActionEvent event) {
String selectedIndex = (String)event.getComponent().getAttributes().get("selectedIndex");
if (selectedIndex == null) {
return;
}
}
}
The attribute "selectedIndex" is always null. Anybody knows what happened here? Thank you.
The variable name "rowIndex" suggests that you've declared this inside an iterating component, such as <p:dataTable>.
This is then indeed not going to work. There's physically only one JSF component in the component tree which is reused multiple times during generating HTML output. The <f:attribute> is evaluated at the moment when the component is created (which happens only once, long before iteration!), not when the component generates HTML based on the currently iterated row. It would indeed always be null.
There are several ways to achieve your concrete functional requirement anyway. The most sane approach would be to just pass it as method argument:
<p:commandButton value="Edit"
action="edit_article_group"
actionListener="#{articleGroupManager.setSelectedRow(rowIndex)}"
ajax="false" disabled="#{editGroupMode=='edit'}" />
with
public void setSelectedRow(Integer rowIndex) {
// ...
}
See also:
JSTL in JSF2 Facelets... makes sense?
How can I pass selected row to commandLink inside dataTable?
Unrelated to the concrete problem, I'd in this particular case have used just a GET link with a request parameter to make the request idempotent (bookmarkable, re-executable without impact in server side, searchbot-crawlable, etc). See also Communication in JSF 2.0 - Processing GET request parameters.

Resources