i just want to print an custom message on a error page, when an exception occurs.
i tried this
if(erroroccured){
FacesMessage message=new FacesMessage("You must login to continue");
context.addMessage(null, message);
FacesContext.getCurrentInstance().getExternalContext().redirect("error.xhtml");
}
In error.xhtml i gave the
<h:messages></h:messages>
tag too.. whenever the exception occurs my page is been redirected perfectly. but i dint get any error msg.
Faces messages are request scoped. A redirect basically instructs the webbrowser to send a brand new HTTP request (that's also why you see the URL being changed in browser address bar). The faces messages which are set in the previous request are of course not available anymore in the new request.
There are several ways to get it to work:
Don't send a redirect. Send a forward instead. You can do it by ExternalContext#dispatch()
FacesContext.getCurrentInstance().getExternalContext().dispatch("error.xhtml");
or by just navigating the usual way if you're already inside an action method
return "error";
Create a common error page master template and use separate template clients for every individual type of error and put the message in the view instead.
<ui:composition template="/WEB-INF/templates/error.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<ui:define name="message">
You must login to continue.
</ui:define>
</ui:composition>
Then you can just redirect to this specific error page like so redirect("error-login.xhtml")
.
Pass some error identifier as a request parameter though the redirect URL like so redirect("error.xhtml?type=login")
and let the view handle it.
<h:outputText value="You must login to continue." rendered="#{param.type == 'login'}" />
Keep the faces messages in the flash scope.
externalContext.getFlash().setKeepMessages(true);
Mojarra has however a somewhat buggy flash scope implementation. With the current releases, this won't work when you need to redirect to a different folder, but it will work when the target page is in the same folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With