Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exception handling in jsf - to print error message in the new page

Tags:

jsf

jsf-2

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.

like image 585
Karthikeyan Avatar asked Feb 29 '12 09:02

Karthikeyan


1 Answers

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.

like image 144
BalusC Avatar answered Sep 19 '22 01:09

BalusC