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.
Originally posted by vinoth thirunavukarasu: Hi, Thanks for your reply. I used these code as a first one and I used try and catch because There is an exception occur when the session.getAttribute("userId") is returns null.
Right, because you are trying to convert it to an int from an Integer right off the bat. You won't need to do that if you treat the user id as an Integer (the object) the entire time, rather than an int (the primitive). You probably don't need an int value anyway - you generally don't need to do math on user ids.
Originally posted by vinoth thirunavukarasu: For that I used the following code.
Your code logic is wrong. The sendRedirect() doesn't immediatelty stop the complete thread and jump out of the method block. The method just continues until it returns or ends. It is a common misunderstanding under greenhorns.