In certain scenarios I want to forcefully logout a user. I'm using Spring Security and the only way I know how to do this is to forward/redirect to /logout (or whatever URL Spring listens to for logout attempts). Since in theory a user could stop his browser from following a redirect, I'd rather do a forward to the logout URL, as it's very important that the logout logic is carried out. Since Spring will always do a redirect after a (un)successful logout, I'm wondering if this will be a problem. So, in short, is redirecting allowed after the request has already been forwarded, or will it result in an IllegalStateException?
So, in short, is redirecting allowed after the request has already been forwarded, or will it result in an IllegalStateException?
No, it's absolutely fine. The response itself has no knowledge of the forwarding - it occurs purely within the internals of the server. Forwarding is simply a mechanism for internal transfer of control from one server component to another.
In contrast, you generally cannot forward after redirecting, since redirecting "commits" the response, and there's no undoing that.
You will only get an IllegalStateException
when the reponse is committed. So if the forwarded resource commits the response before redirecting, then you will get IllegalStateException
. The response is committed when the response headers are already been sent. This can happen when you write a byte to the response body and flush it. A redirect requires an uncommitted response because a redirect needs to be done by setting a Location
header with a blank body.
In a decent MVC approach, the JSP is part of the response, so whenever you send a redirect from inside a JSP by either a scriptlet or a JSTL <c:redirect>
, then you will risk IllegalStateException
. But if you don't do that anywhere, there's nothing to worry about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With