The
IllegalStateException is almost always associated with trying to change a response headers when the response is already committed.
So in your example you have 2 sendRedirect() calls. The sendRedirect is a header response that tells the client that it should go to a different page. It should be called BEFORE any other response is sent to the client. So if you have any other output to the response before the sendRedirect occurs, then you will get this error.
The sendRedirect will also commit the response (send a response to the client), so no changes can be made to the response AFTER sending the response. This comes into play at least twice in your code:
So if there is an exception that occurs when session.getAttribute gets called and the value is cast to an Integer, then a response.sendRedirect() will be sent to the client, but then the catch statement ends and the method will continue, bringing you to:
Where the comparison may be made and found to be true and a second sendRedirect() could be called, causing the same error.
Finally, what if you do get an exception when getting the user id, but the user is not equal to 0 (which it may not be, it may be null)? Then the rest of the method still runs and tries to send a response to the client, ending in the same error message.
Your code is better off with either if/else to make sure only one execution path is followed:
I would guess that the error is coming because you are using the sendRedirect after already sending some data to the client rather than before. When you sendRedirect before sending data to the client the error usually is hidden in the log files where you aren't likely to see it, though other weird behavior may come up.
So make sure you do the sendRedirect first thing, do nothing before doing the sendRedirect, and in the case when sendRedirect is used, make sure nothing else happens after the sendRedirect.