JSF 2 navigation always from root folder

2019-06-08 06:26发布

问题:

I have a JSF 2 application with the following xhtml structure:

--webapp --index.xhtml --folder1 --targetPage.xhtml --folder2 --otherPage.xhtml

I have a managed bean called TargetPageBean with the following method:

public String navigateToTargetPage() {

    if( isOnIndexPage() ) {
        return "folder1/targetPage.xhtml?faces-redirect=true";
    } else {
        return "targetPage.xhtml?faces-redirect=true";
    }
}

This would work fine in these two cases:

  • I navigate just from the index page to the target page
  • I am already on the target page and I navigate to this page again

But this approach is pretty bad because my tree strcuture could be deeper and I could want to move to the target page from nearly everywhere. Can I tell JSF that it should always redirect from the "root" so that I just have to return folder1/targetPage.xhtml?faces-redirect=true? (I do not want to use the explicit navigation via the faces-config file)

回答1:

You can use redirect with full request path:

getFacesContext().getExternalContext().redirect(getRequest().getContextPath() +
    "/page.jsf?" + Constants.CONSTANT_NAME + "=" + bean.getSomeValue());

where

protected HttpServletRequest getRequest() {
    return (HttpServletRequest) getFacesContext().getExternalContext().getRequest();
}
protected FacesContext getFacesContext() {
    return FacesContext.getCurrentInstance();
}