5
votes

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.

1
no its not, that question deals about validation errors msgs, am asking about exception handling where i need to redirect to another page to print my custom message. But no redirection happens in that question... i have no problem in printing a validation message in the same page.. problem exist mainly in the redirection it seems..Karthikeyan

1 Answers

9
votes

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:

  1. 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";
    
  2. 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").

  3. 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'}" />
    
  4. 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.