Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF redirect on page load

Tags:

java

redirect

jsf

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

like image 628
James P. Avatar asked Dec 10 '22 17:12

James P.


2 Answers

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.

like image 171
BalusC Avatar answered Dec 25 '22 17:12

BalusC


Yes:

if(!isLoggedIn) {
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}
like image 22
Michael Bavin Avatar answered Dec 25 '22 18:12

Michael Bavin