JSF - Save face messages after redirecting from @PostConstruct

I have page1 with a button that moves to page2, page 2 adds some messages and goes to page1. I want to display these messages on page 1. I have tried many solutions, but nothing works.

Sample code page1.xhtml:

<p:commandButton value="edit" action="#{bean1.edit}"/> 

In a managed bean:

 public String edit() { return "page2?faces-redirect=true"; } 

page2 bean

 @PostConstruct private void postConstruct() { Faces.getFlash().setKeepMessages(true); Messages.addFlashGlobalError("cannot edit!"); Faces.navigate("page1?faces-redirect=true"); } 

Both beans are visible and both pages have <p:messages> at the end of the body.

+2
source share
3 answers

First of all, I'm not quite sure that @PostConstruct is the best place to do the redirection. Cm. . With this google picked up this one and it looks reasonable. Try redirecting facelets on the page itself with the preRender event tag closer to the top of the page. Greetings

+1
source

This can happen if @PostConstruct is called too late. Apparently, the bean is referenced and thus constructed for the first time relatively "late" in the view (for example, at the very bottom). At this point, the answer may already be fixed, which is the point of no return. You can no longer switch to another species.

Basically you want to call the init() method before rendering the answer. In OmniFaces, you can use the following approach in page2.xhtml :

 <f:metadata> <f:viewParam name="dummy" /> <f:event type="postInvokeAction" listener="#{bean.init}" /> </f:metadata> 

(you can remove <f:viewParam name="dummy" /> if you already have your own viewing options on this page, just to complete the INVOKE_ACTION phase, see also the postInvokeAction demo page )

and just a simple <f:event listener> method:

 public void init() { Messages.addFlashGlobalError("cannot edit!"); Faces.navigate("page1?faces-redirect=true"); // Or Faces.redirect("page1.xhtml"); } 

Faces.getFlash().setKeepMessages(true); not required since Messages#addFlashGlobalError() already does this. Keep in mind that in Mojarra, the Flash area will not work if navigation is specified in a different folder in the URL. Both pages must be in the same folder in the URL. This is recorded in the upcoming Mojarra 2.1.14.

+2
source

Just use nevigation. This will certainly work. check the following code. public String redirect () throws Exception {FacesContext.getCurrentInstance (). AddMessage ("Msg1", the new FacesMessage ("Message 1 is")); //FacesContext.getCurrentInstance (). GetExternalContext (). Redirect ("/Sam/page2.jsf"); return "page2"; }

-1
source

All Articles