How can Flash scope help in implementing the PostR

2019-05-06 17:44发布

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 ?

1条回答
地球回转人心会变
2楼-- · 2019-05-06 18:33

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).

查看更多
登录 后发表回答