Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving FacesMessage after redirect for presentation through <h:message> in JSF [duplicate]

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?

like image 676
brandizzi Avatar asked Feb 28 '11 02:02

brandizzi


2 Answers

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"

like image 175
styx Avatar answered Oct 17 '22 23:10

styx


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" />
like image 41
heronsanches Avatar answered Oct 17 '22 21:10

heronsanches