【问题标题】:Servlet doesn't execute response.sendRedirect(addressPath); , but does execute response.sendRedirect() without pathServlet 不执行 response.sendRedirect(addressPath); ,但执行 response.sendRedirect() 没有路径
【发布时间】:2023-03-05 17:43:01
【问题描述】:
考虑以下层次结构:
当我像这样发送重定向时:
response.sendRedirect("error404.jsp"); // no path here !!!
我到达页面 error404.jsp 。
但是当我使用路径时:
String addressPath = "/WEB-INF/results/admin/adminPage.jsp";
response.sendRedirect(addressPath); // with path !!!
我得到 404:
HTTP Status 404 -
type Status report
message
description The requested resource is not available.
Apache Tomcat/7.0.50
我在这里做错了什么?
非常感谢!
【问题讨论】:
标签:
java
jsp
tomcat
servlets
web-applications
【解决方案1】:
因为客户端无法访问 WEB-INF 下的内容。如果您希望 JSP 可访问,请不要将它们放在 WEB-INF 下。
或者,要使客户端可以访问 WEB-INF 下的任何内容,您必须将其映射到 web.xml 中的 URL:
<servlet>
<servlet-name>adminPage</servlet-name>
<jsp-file>/WEB-INF/results/admin/adminPage.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>adminPage</servlet-name>
<url-pattern>/adminPage/*</url-pattern>
</servlet-mapping>
然后使用您映射的 url 模式:
response.sendRedirect("./adminPage/");
这是相当没有意义的。您可以使用 WEB-INF 之外的 JSP 并使用 URL 重写过滤器来实现基本相同的目标。简而言之,您可能没有真正的理由将您的 JSP 置于 WEB-INF 之下。
【解决方案2】:
见javadoc
此方法可以接受相对 URL;servlet 容器必须
在发送之前将相对 URL 转换为绝对 URL
回复客户。 如果位置是相对的,没有前导
'/' 容器将其解释为相对于当前请求
URI。如果位置与前导 '/' 容器相关
将其解释为相对于 servlet 容器根目录。 如果
位置与两个前导“/”相对,容器解释它
作为网络路径参考(参见 RFC 3986:统一资源标识符
(URI):通用语法,第 4.2 节“相对引用”)。
请注意,该参数不是 servlet 上下文中的路径,就像 RequestDispatcher 将使用的那样,它作为 302 响应的 Location 标头中使用的 URL。
所以这个
String addressPath = "/WEB-INF/results/admin/adminPage.jsp";
response.sendRedirect(addressPath); // with path !!!
将转换为带有标头的 302 响应
Location: http://whateverhost.com/WEB-INF/results/admin/adminPage.jsp
你没有处理程序,所以 404。
另一方面,这个
response.sendRedirect("error404.jsp"); // no path here !!!
变成
Location: http://whateverhost.com/context-path/error404.jsp
由于error404.jsp 在WEB-INF 之外,它可以访问,因此由JSP servlet 呈现并作为响应返回。