Jsf 在会话bean@PostConstruct中重定向

Jsf 在会话bean@PostConstruct中重定向,jsf,redirect,Jsf,Redirect,我有一个JSF 2.0应用程序,它有一个从home.xhtml访问的会话bean,如下所示: @Named(value = "home") @SessionScoped public class Home implements Serializable{ @PostConstruct public void init() { // Retrieve database data here try { } catch (Exception ex) {

我有一个JSF 2.0应用程序,它有一个从home.xhtml访问的会话bean,如下所示:

@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");


        }
    }
}
我想做的是,如果数据库检索失败,重定向到error.xhtml页面。在上面的init方法中是如何做到这一点的?

您可以使用该方法

FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.redirect("page2.xhtml");

无需手动干扰重定向。直接抛出异常即可

@PostConstruct
puclic void init() throws Exception { // Please be more specific, e.g. SQLException.
    // Retrieve database data here without try/catch block.
}
它将在HTTP 500错误页面中结束,该页面的位置(以及外观)可以通过
web.xml
进行定制:

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

500
/WEB-INF/errorpages/500.xhtml

如果您还想讨论ajax请求的例外情况,请直截了当地回答:

@onepotato:不要再陈述假设了。问一个问题并陈述观察结果。我肯定会注意到在我未来的互动中。嗨@BalusC,如果用户名或密码错误,我可以使用相同的方法重定向回登录页面吗?还是有其他更可接受的方法来实现这一点?