File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes Why get IllegalStateException when redirect in Servlet Filter? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Why get IllegalStateException when redirect in Servlet Filter?" Watch "Why get IllegalStateException when redirect in Servlet Filter?" New topic
Author

Why get IllegalStateException when redirect in Servlet Filter?

Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
I have a servlet filter and to try and narrow down the cause of the error, it does only two things: redirect and call doFilter(...). For some reason this keeps throwing the error: IllegalStateException. (I'm using Jetty) The code:



This throws the following error:


Here's the weird thing: it throws the exception but will still show "test-redirect.jsp". If I take out the "chain.doFilter(...)" statement, then it doesn't throw the error, but obviously also doesn't show my page. Any idea what's going on? Am i not allowed to redirect in a filter?
[ September 08, 2006: Message edited by: Bear Bibeault ]
Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
In case anyone's wondering, here's the reason why:

When you send a redirect, you should NOT continue the chain. A redirect message/request will then be sent to the client via HTTP headers, basically requesting that they request this new page ("test-redirect.jsp" in this example). Since browsers automatically do this, it then returns to the filter which now should continue the chain.

The correct code then:
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61415
    
  67

Originally posted by Dan Bizman:

When you send a redirect, you should NOT continue the chain.


Exactly. Once you have redirected or forwarded in any resource. filter or otherwise, you should do nothing else. Conventionally, a redirect or forward is either followed by a return statement, or is the last statement in a conditional.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
wood burning stoves
 
subject: Why get IllegalStateException when redirect in Servlet Filter?