簡體   English   中英

Servlet不執行response.sendRedirect(addressPath); ,但會執行沒有路徑的response.sendRedirect()

[英]Servlet doesn't execute response.sendRedirect(addressPath); , but does execute response.sendRedirect() without path

考慮以下層次結構:

在此處輸入圖片說明

當我這樣發送重定向時:

    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

我在這里做錯了什么?

非常感激 !

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.jspWEB-INF外部,因此它是可訪問的,因此由JSP servlet呈現並作為響應返回。

因為客戶端無法訪問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下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM