Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it allowed to redirect a request after forwarding?

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?

like image 266
kaqqao Avatar asked Dec 27 '22 20:12

kaqqao


2 Answers

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.

like image 172
skaffman Avatar answered Jan 13 '23 15:01

skaffman


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.

like image 22
BalusC Avatar answered Jan 13 '23 17:01

BalusC