Redirect in @PostConstruct causes IllegalStateException

Redirecting in a @PostConstruct might be too late if the response is already committed. I.e. when the first few bytes of the response are already been sent to the client. This is a point of no return. That can in your case happen when the backing bean is referenced (and thus constructed) for the first time relatively late in the view, maybe about halfway or in the end.

You could solve this in one of the following ways:

  1. Reference the bean for the first time as early as possible in the view.

  2. Use <f:event type="preRenderView"> instead of @PostConstruct. This will invoke the method right before the render response starts (thus, before any bit is been sent to the response). Or, when you’re on JSF 2.2 already, use the <f:viewAction>. Additional advantage is that the <f:viewAction> can return a navigation case outcome like return bolagsSok_company?faces-redirect=true" without the need to fiddle with ExternalContext#redirect().

  3. Increase the default Facelets buffer size by javax.faces.FACELETS_BUFFER_SIZE context param in web.xml to about the size of the largest HTML response.

See also:

Leave a Comment