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.