JSF redirect on page load

前端 未结 4 623
無奈伤痛
無奈伤痛 2021-02-10 18:41

Short question: Is it possible to do a redirection, say when a user isn\'t logged in, when a page is rendered?

相关标签:
4条回答
  • 2021-02-10 19:16

    In a PhaseListener try:

    FacesContext ctx = FacesContext.getCurrentContext();
    ctx.getApplication().getNavigationHandler()
         .handleNavigation(ctx, null, "yourOutcome");
    
    0 讨论(0)
  • 2021-02-10 19:19

    Yes:

    if(!isLoggedIn) {
    FacesContext.getCurrentInstance().getExternalContext().redirect(url);
    }
    
    0 讨论(0)
  • 2021-02-10 19:21

    For that you should use a Filter.

    E.g.

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { 
        if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
            ((HttpServletResponse) response).sendRedirect("error.jsf"); // Not logged in, so redirect to error page.
        } else {
            chain.doFilter(request, response); // Logged in, so just continue.
        }
    }
    

    Here I assume that the User is been placed in the session scope as you would normally expect. It can be a session scoped JSF managed bean with the name user.

    A navigation rule is not applicable as there's no means of a "bean action" during a normal GET request. Also doing a redirect when the managed bean is about to be constructed ain't gong to work, because when a managed bean is to be constructed during a normal GET request, the response has already started to render and that's a point of no return (it would only produce IllegalStateException: response already committed). A PhaseListener is cumbersome and overwhelming as you actually don't need to listen on any of the JSF phases. You just want to listen on "plain" HTTP requests and the presence of a certain object in the session scope. For that a Filter is perfect.

    0 讨论(0)
  • 2021-02-10 19:22

    You can use a PhaseListener to specify when you want to do redirection.

    0 讨论(0)
提交回复
热议问题