开发者

JSF redirect on page load

Short questi开发者_运维问答on: Is it possible to do a redirection, say when a user isn't logged in, when a page is rendered?


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.


Yes:

if(!isLoggedIn) {
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}


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


In a PhaseListener try:

FacesContext ctx = FacesContext.getCurrentContext();
ctx.getApplication().getNavigationHandler()
     .handleNavigation(ctx, null, "yourOutcome");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜