Submitting a JSF2 form does not reload the collection on the same page
JSF 2.0 (mojarra) application. I have a very trivial form for adding an item
<h:form>
#{msg['add custom title']}:<br />
<table>
<tr>
<td>#{msg['heaading']}:</td>
<td><h:inputText value开发者_如何学Go="#{titlesBean.title.heading}"></h:inputText></td>
</tr>
<tr>
...
</tr>
</table>
<h:commandButton action="#{titlesBean.addTitle}" value="#{msg['g.save']}" />
</h:form>
And then on the same page I have a list of all the items already added:
<h:dataTable id="manualTitlesForm" value="#{titlesBean.manualTitles}" var="title" border="1" cellspacing="0">
<h:column>
<f:facet name="header">#{msg['heaading']}</f:facet>
#{title.heading}
</h:column>
...
<h:column>
<f:facet name="header">#{msg['actions']}</f:facet>
<h:form>
<h:commandButton action="#{titlesBean.editManualTitle(title)}" value="#{msg['g.edit']}" />
<h:commandButton action="#{titlesBean.deleteManualTitle(title.id)}" value="#{msg['g.delete']}" />
</h:form>
</h:column>
</h:dataTable>
The code in the bean code is super simple:
@Controller
@Scope(Scopes.REQUEST)
public class TitlesBean {
private List<JTitle> manualTitles;
@PostConstruct
private void init() {
this.manualTitles = titlesManager.getManualTitles();
}
public String addTitle() {
title.setCreated(new Date());
title.setManual(true);
try {
titlesManager.addTitle(title);
title = new JTitle();// this is added, delete from the variable. only if no exception though !!!
UserMessagesBean.addMessage("saved");
} catch (Exception e) {
UserMessagesBean.setValidationException(e.getMessage());//different exception added
}
return null;
}
public List<JTitle> getManualTitles() {
return manualTitles;
}
}
Now the problem is that getManualTitles()
is called as many times as the number of titles I have, which causes for example 12 calls to the DB, instead of one. Why is this happening is beyond my understanding. I can fix this with caching the manual titles in the bean. This is not my main problem.
The problem is that addTitle()
is called AFTER getManualTitles()
. In fact getManualTitles()
is called for example 10 times, then addTitle()
, then two more times the getManualTitles()
method. This makes me think that this is some kind of parallel execution which causes my page to show only the 12 old records instead of 13. I have to reload the page, then 13 is shown.
UPDATED: now caches the list. Problem still not solved.
WHY? How can I fix this?
This is a quick fix, but not a real solution. Redirect the result of addTitle()
:
Add the following to addTitle()
:
...
FacesContext.getCurrentInstance().getExternalContext()
.redirect("manualTitles.jsf");
return null;
}
精彩评论