JSF - Keep Faces Messages after redirect from @PostConstruct

南楼画角 提交于 2019-12-11 03:27:52

问题


I have page1 with button that navigates to page2, page 2 add some messages and navigates back to page1. I want display those messages on page1. I've tried many solutions, but nothing work.

Sample code page1.xhtml:

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

In the managed bean:

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

page2 managed bean

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

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


回答1:


First of all, I'm not entirely sure that the @PostConstruct is the best place to perform a redirect. See this. That being said, google turned up this and it looks reasonable. Try redirecting within the facelets page itself with a preRender event tag close to the top of the page. Cheers




回答2:


That can happen if the @PostConstruct is invoked too late. Apparently the bean is referenced and thus constructed for the first time relatively "late" in the view (e.g. in the very bottom). At that point, the response may be already committed which is a point of no return. You cannot navigate to a different view anymore.

You basically want to invoke the init() method before render response. With 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 the <f:viewParam name="dummy" /> if you already have your own view parameters on that page; it's just to ensure that INVOKE_ACTION phase is executed, see also 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");
}

The Faces.getFlash().setKeepMessages(true); is unnecessary as Messages#addFlashGlobalError() already does that. Please keep in mind that in Mojarra the Flash scope won't work if the navigation is to a different folder in the URL. The both pages have to be in the same folder in the URL. This is fixed in upcoming Mojarra 2.1.14.




回答3:


Just use nevigation. It will surely work. check following code. public String redirect() throws Exception { FacesContext.getCurrentInstance().addMessage("Msg1",new FacesMessage("Message 1 is")); //FacesContext.getCurrentInstance().getExternalContext().redirect("/Sam/page2.jsf"); return "page2"; }



来源:https://stackoverflow.com/questions/12708156/jsf-keep-faces-messages-after-redirect-from-postconstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!