JSF redirect to page load

Short question: is it possible to redirect, say, when the user is not logged in, when the page is displayed?

+4
source share
4 answers

For this you should use Filter .

eg.

 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 User is placed in the session area, as you usually expect. This may be a session-driven JSF bean named User .

The navigation rule does not apply, since there are no bean means during a normal GET request. In addition, performing a redirect when a managed bean should be constructed does not work gong, because when a managed bean needs to be constructed during a normal GET request, the response has already begun to display and that the point is without return (it would only IllegalStateException: response already committed ). PhaseListener is cumbersome and overwhelming since you actually don't need to listen to any of the JSF phases. You just want to listen for β€œsimple” HTTP requests and the presence of a specific object in the session area. For this, the filter is ideal.

+8
source

Yes:

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

You can use PhaseListener to indicate when you want to redirect.

+1
source

In PhaseListener try:

 FacesContext ctx = FacesContext.getCurrentContext(); ctx.getApplication().getNavigationHandler() .handleNavigation(ctx, null, "yourOutcome"); 
+1
source

Source: https://habr.com/ru/post/1303221/


All Articles