1

I have a JSF 2.0 app that has a session bean that is accessed from home.xhtml, as follows:

@Named(value = "home")
@SessionScoped
public class Home implements Serializable{

@PostConstruct
    public void init() {
// Retrieve database data here
        try {
        } catch (Exception ex) {
            System.out.println("EXCEPTION");


        }
    }
}

What I want to do is, if the database retrieval fails, redirect to error.xhtml page. How is this done in the init method above?

CaptainMorgan
  • 1,051
  • 2
  • 22
  • 51

2 Answers2

2

You can use External Context's redirect(java.lang.String) method.

FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.redirect("page2.xhtml");
Kishor Prakash
  • 7,381
  • 10
  • 53
  • 88
1

No need to manually mess with redirecting. Just throw the exception outright.

@PostConstruct
puclic void init() throws Exception { // Please be more specific, e.g. SQLException.
    // Retrieve database data here without try/catch block.
}

It will already end up in a HTTP 500 error page whose location (and thus the look'n'feel) can be customized by web.xml:

<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/errorpages/500.xhtml</location>
</error-page>

In case you'd like to also cover exceptions on ajax requests, head to this answer: What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • @onepotato: Just stop stating assumptions. Ask a question and state the observations. – BalusC May 28 '14 at 07:55
  • I will surely note that in my future interactions. – Bnrdo May 28 '14 at 07:58
  • Hi @BalusC, can I use same approach to redirect back to login page if username or password is wrong? Or is there another more acceptable way to perform this? – Anatoly Jul 01 '14 at 12:56