为什么 Head First 书在将请求从 Servlet 转发到 JSP 时使用“/”?

问题描述

在阅读Head First JSP 和 Servlets 时,我了解到正斜杠 (/) 用于表示容器的根。所以请注意在 this example from the book 中如何使用 (/) 时没有 myApp

但是当他们转发请求(而不是使用response.sendRedirect)时,他们指定(/)。注意这张图中他们写/result.jsp的部分:

enter image description here

我现在有点困惑。我有一个名为 myApp 的项目。在里面我有 index.htmlservlet.classresult.jsp

我在浏览器中最终得到的是 http://localhost:8080/myApp/result.jsp。但是在阅读我在顶部提供的链接时,它应该是 http://localhost:8080/result.jsp。因为正如我所说(链接也是如此),正斜杠 (/) 代表容器的根。而 root 是 http://localhost:8080 而不是 http://localhost:8080/myApp

最奇怪的是它可以双向工作 - 如果我输入 result.jsp/result.jsp。有人可以清除这个,因为它正在杀死我:)

我最困惑的是 /result.jsp 是如何工作的,什么时候它应该带我们到 http://localhost:8080/result.jsp 而我的 result.jsp 在 myApp 而不是在容器内强>技术上。

解决方法

根据documentation

如果路径以“/”开头,则将其解释为相对于当前上下文根。

所以路径是相对于你的上下文根,而不是你的整个应用服务器。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...