Search code examples
jakarta-eejsf-2prettyfaces

PrettyFaces redirect doesn't work with preRenderView event


i have a preRender view event in my bean, and i make some validation in it on the user, and when some condition occur, i redirect the user to login page using prettyFaces, but the redirection doesn't seem to work, i don't know why, here's the code:

JSF:

<f:event type="preRenderView" listener="#{myBean.preRender}" />

Managed Bean:

public String preRender() {
        log.debug("preRender myPage for user " + userId);
        try {
            User user = userService.getUserById(userId);
            if (!user.isSomeCondition()) {
                log.debug("Bad Condition");
                return "pretty:login";
            }
        } catch (Exception e) {
            log.error("Error in preRender myPage for user "
                    + userId);
            return "pretty:login";
        }

        return null;
    }

Solution

  • You can't navigate by returning a string in action listener methods. It would be completely ignored. It is only possible in real action methods as provided by <h:commandXxx action="...">.

    What you can do instead, is to manually invoke the NavigationHandler#handleNavigation() .

    FacesContext context = FacesContext.getCurrentInstance();
    NavigationHandler navigator = context.getApplication().getNavigationHandler();
    navigator.handleNavigation(context, null, "pretty:login");