I have what I suppose is a common problem: some managed bean has an action which adds some messages to the context:
FacesMessage fm = new FacesMessage("didn't work");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext.getCurrentInstance().addMessage(null, fm);
return "some-outcome";
Then I map the outcome in faces-config.xml
and configure it to
<navigation-case>
<from-outcome>some-outcome</from-outcome>
<to-view-id>/view.xhtml</to-view-id>
<redirect/>
</navigation-case>
In view.xhtml
I present the message:
<h:message globalsOnly="true" />
However, it does not work because the message is lost when the redirect is executed.
How would I solve it? I found this amazing post explaining how to do it using a PhaseListener
but I believe this situation is too common to have to be solved this way. Am I wrong? Should I create the PhaseListener
? Or is there some other, standard solutions?
Great answer from BalusC as usual!
I just want to add, when i used his code to set the keepMessages property, it was not set for the session, but only for this request (despite what it says in the Javadocs).
I put the following code in my header.xhtml
<c:set target="#{flash}" property="keepMessages" value="true" />
Now it works on every page, without me having to set it every time i need it in the backing bean.
You need JSTL for this and dont forget to put the following in your xhtml header:
xmlns:c="http://java.sun.com/jsp/jstl/core"
JSF 2.2
Into the bean:
FacesContext facesContext = FacesContext.getCurrentInstance();
Flash flash = facesContext.getExternalContext().getFlash();
flash.setKeepMessages(true);
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "yourMessage", null));
return "namePage?faces-redirect=true";
Into the namePage
Change
<h:message globalsOnly="true" />
to
<h:messages globalsOnly="true" />
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