4

I was reading Balusc blog on PRG pattern in JSF where it is mentioned that :

This article is targeted on JSF 1.2. For JSF 2.0, this can easier be achieved using the new Flash scope.

I wanted to find out how can flash scope help us in achieving the same ?

Geek
  • 26,489
  • 43
  • 149
  • 227

1 Answers1

3

Call Flash#setKeepMessages() with true before render response phase to instruct JSF to store the faces messages in the flash scope and add faces-redirect=true query string parameter to the outcome to perform a redirect.

public String submit() {
    // ...

    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", null));
    context.getExternalContext().getFlash().setKeepMessages(true);
    return "nextpage?faces-redirect-true";
}

This way there's no need for a phase listener which collects the faces messages from the faces context and stores them in the session before redirect and removes them from the session on the firstnext request and re-adds them to the faces context after redirect.

The flash scope works roughly the same way. The messages are stored in the session by an unique identifier which is in turn been passed as a cookie in the response and those messages (and the cookie) are been removed from the session on the firstnext request which has passed the cookie back (which is, after all, a more robust implementation although the chance is very little that an enduser will send 2 HTTP requests on the same session at exactly the same moment — or it must be a robot).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • what do you mean by "firstnext" request ? Can you elaborate ? – Geek Oct 30 '12 at 14:41
  • The first next HTTP request (in the same session) which comes in after the current response is completed. In case of a response with a redirect, you'd usually assume that it's the redirected request itself. – BalusC Oct 30 '12 at 14:42
  • If you have a hard time in understanding HTTP request, HTTP response and HTTP session, then you may find this answer helpful: http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading/3106909#3106909 – BalusC Oct 30 '12 at 14:45