tags:

views:

41

answers:

2

The api for ServletContext#getRequestDispatcher() says:

This method returns null if the ServletContext cannot return a RequestDispatcher.

and

Returns: a RequestDispatcher object that acts as a wrapper for the resource at the specified path, or null if the ServletContext cannot return a RequestDispatcher

For what reason would the ServletContext not be able to return a RequestDispatcher? At first I figured it would be if an invalid path was passed but that doesn't return null, it results in a 404 on the browser.

I am checking for null before calling the forward() method and in the logs I can see that once in awhile the RequestDispatcher is null but I don't know why and I can't find out how to duplicate it.

Thanks

Update

Like Fazal suggested I tried created a RequestDispatcher to 'http://www.google.com/' to see what would happen. This caused an IllegalArgumentException

java.lang.IllegalArgumentException: Path http://www.google.com/ does not start with a "/" character

The Exception was caught in my try/catch block so I never got the chance to check if the RequestDispatcher was null or call the forward() method.

So there must be another way for the ServletContext#getRequestDispatcher() method to return null without throwing an Exception?

+1  A: 

I have seen this issue intermittently. But for me this only happens, if you are trying to go to a valid patch which is not in the document root. E.g. Your Server is running at http://localhost/ and I do a forward to a URL like http://www.google.com. Not sure if you run into this issue

Fazal
Hmm, I decided to try creating a RequestDispatcher to http://www.google.com/ and it threw an IllegalArgumentException because the Path does not start with a "/" character.
bmeding
+1  A: 

Tomcat returns null for path outside of the current context, such as /../foo (but Jetty doesn't, so it's implementation-specific).

axtavt
Ahh, I see I was missing the '../'. I am running on Tomcat and you're right it did return null. Also I noticed that if the path passed to getRequestDispatcher() is null then it will return null too.
bmeding