Maciej Ziarko
Maciej Ziarko

Reputation: 12084

ServletRequest.getRequestDispatcher() for non-existent files/resources

Currently I'm preparing for Java EE Web Component Developer exam.

In both exam study guide and Servlet API Java docs I found that method

ServletRequest.getRequestDispatcher()

returns

null if the servlet container cannot return a RequestDispatcher.

When I tried it with non-existent static file I actually got non-null value. And forward resulted in 404 sent to client. Same effect for non-existent servlet. I use Apache Tomcat 7.0.

Does it mean that this behaviour isn't defined and is left to implementer's choice? What do they (Java docs authors) mean by "servlet container cannot return a RequestDispatcher"? I tried to look for it in JSR spec but wasn't able to find answer.

Upvotes: 2

Views: 667

Answers (1)

Perception
Perception

Reputation: 80603

This is what the Servlet 3.0 specification has to say about dispatcher behavior:

The getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext and begin with a ‘/’, or be empty. The method uses the path to look up a servlet, using the servlet path matching rules in Chapter 12, “Mapping Requests to Servlets”, wraps it with a RequestDispatcher object, and returns the resulting object. If no servlet can be resolved based on the given path, a RequestDispatcher is provided that returns the content for that path.

Nowhere does it mentioning returning null if a matching servlet cannot be found for the dispatch path. Instead it states that the 'content' found at the dispatch path will be found, which I translate as meaning an implementation can simply allow the container to absolutely resolve the path (which in your scenario yields a 404).

As far as the Javadoc though, it seems documented with the broadest use case possible, aka, if the container cannot create a dispatcher for any reason then it will return a null object (as opposed to throwing an exception). This may be due to a technical problem in the implementation, or may be actually valid (e.g JAX-RS implementations can access some level of the Servlet infrastructure, but cannot use the servlet context or dispatcher).

Upvotes: 2

Related Questions