Search code examples
jsfjsf-2

JSF permanent redirect using a bean on a preRenderView event


Is there a way to permanently redirect to a page on preRenderEvent view using faces-config navigation?

For example, after login it will redirect on a page and on that page I need to know the role of a user so that I can redirect him to the correct page.

I'm using this to redirect:

<f:metadata>
    <f:event listener="#{loginRedirectBean.redirect}" type="preRenderView"></f:event>
</f:metadata>

public void redirect() throws IOException {
    if (identity.isLoggedIn()) {
        if(hasRole("admin")) {
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
            context.redirect("faces.admin");
        }
    }
}

Solution

  • Since faces-config navigation. I've just used a file given a role.

    public void redirect() throws IOException {
        String redirectUrl = "login.jsf";
        if (identity.isLoggedIn()) {
            try {
                User user = ((PicketlinkUser) identity.getAccount()).getUser();
                if (user.hasRole(Role.ROLE_ADMIN)) {
                    redirectUrl = "pages/secured/" + Role.ROLE_ADMIN + "/index.jsf";
                } else if (user.hasRole(Role.ROLE_BRIDE)) {
                    redirectUrl = "pages/secured/" + Role.ROLE_BRIDE + "/index.jsf";
                } else if (user.hasRole(Role.ROLE_VENDOR)) {
                    redirectUrl = "pages/secured/" + Role.ROLE_VENDOR + "/index.jsf";
                } else if (user.hasRole(Role.ROLE_COLLABORATOR)) {
                    redirectUrl = "pages/secured/" + Role.ROLE_COLLABORATOR + "/index.jsf";
                } else {
                    log.info("user={} has no valid role?", user);
                    redirectUrl = "index.jsf";
                }
            } catch (NullPointerException e) {
                log.error("no role?={}", e.getMessage());
            }
        } else {
            log.error("isNotLoggedIn, redirect to login.");
        }
    
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        context.redirect(redirectUrl);
    }