12

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?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
brandizzi
  • 26,083
  • 8
  • 103
  • 158

2 Answers2

6

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"

styx
  • 421
  • 8
  • 15
  • 1
    I think this is the link for BalusC's post: http://balusc.blogspot.com/2007/03/post-redirect-get-pattern.html – seanf Jun 18 '12 at 05:11
5

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" />
MHosafy
  • 176
  • 3
  • 12
heronsanches
  • 524
  • 7
  • 12