ServletContext#getRequestDispatcher() 的 API说:
This method returns null if the ServletContext cannot return a RequestDispatcher.
和
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
为什么 ServletContext 不能返回 RequestDispatcher?起初我认为如果传递了无效路径但不返回 null,则会在浏览器上导致 404。
我在调用 forward() 方法之前检查是否为 null,在日志中我偶尔会看到 RequestDispatcher 为 null,但我不知道为什么,也不知道如何复制它。
谢谢
更新
正如 Fazal 建议的那样,我尝试为“http://www.google.com/”创建一个 RequestDispatcher,看看会发生什么。这导致了 IllegalArgumentException
java.lang.IllegalArgumentException: Path http://www.google.com/ does not start with a "/" character
异常是在我的 try/catch block 中捕获的,所以我没有机会检查 RequestDispatcher 是否为 null 或调用 forward() 方法。
那么 ServletContext#getRequestDispatcher() 方法必须有另一种方法来返回 null 而不抛出异常吗?
最佳答案
Tomcat 为当前上下文之外的路径返回 null
,例如 /../foo
(但 Jetty 不会,因此它是特定于实现的)。
关于java - ServletContext 何时返回空的 RequestDispatcher?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3815028/