1

I get an IllegalStateException when redirecting from a preRenderView event. I have worked around it by just ingoring the exception. Is there a cleaner way to achieve the same result?

@Named
@RequestScoped
public class LogoutBean implements Serializable
{
    public void preRenderView(ComponentSystemEvent e)
    {
        userSessionBean.logout();
        FacesContext ctx = FacesContext.getCurrentInstance();
        try
        {
            ctx.getApplication().getNavigationHandler().handleNavigation(ctx, null, "/pages/index?faces-redirect=true");
        }
        catch (IllegalStateException exc)
        {
            // Ignore. This exception is caused by redirecting after the response is already committed. The redirect works anyway.
        }
    }

    @Inject
    private UserSessionBean userSessionBean;
}
Steve
  • 8,066
  • 11
  • 70
  • 112

1 Answers1

0

I'd suggest to send a redirect by ExternalContext#redirect() instead.

public void preRenderView(ComponentSystemEvent e) throws IOException {
    FacesContext.getCurrentInstance().getExternalContext().redirect("pages/index.xhtml");
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • `FacesContext.getCurrentInstance().responseComplete();` had no effect. I'm a bit uncomfortable with the 2nd option because I lose the view ID abstraction. – Steve Jun 29 '11 at 20:31
  • Hmm, oh of course it would have no effect. You're inside the render response phase already! I edited the answer to remove the suggestion. – BalusC Jun 29 '11 at 20:33
  • Another problem is that I'm using UrlRewriteFilter and it seems the explicit redirect bypasses the URL encoder which UrlRewriteFilter relies on. – Steve Jun 29 '11 at 20:47