1. 程式人生 > >java web中路徑格式使用案例總結,即問題:要不要以“/”開頭?

java web中路徑格式使用案例總結,即問題:要不要以“/”開頭?

首先可以確定相對路徑不需要以“/”開頭,在Java web裡用到的絕對路徑要以“/”開頭,因為“/”表示根目錄(即伺服器),然後“/”後面加上專案名/......

接著要考慮的關鍵問題是,哪裡用相對路徑、相對誰?,哪裡用絕對路徑?

很難從個例當中總結出普適的規律,所以我把自從接觸Java web以來遇到的情況幾乎都測試了一遍。

補充:以下為路徑中所使用的幾個特殊符號

  •  .:代表目前所在的目錄,相對路徑。如:<ahref="./abc">文字</a><img src="./abc" />
  •   ..:代表上一層目錄,相對路徑。如:<ahref="../abc">
    文字</a><img src="../abc" />
  •   ../../:代表的是上一層目錄的上一層目錄,相對路徑。如:<imgsrc="../../abc" />
  •  /:代表根目錄,絕對路徑。如:<ahref="/abc">文字</a><img src="/abc" />
  •  D:/abc/:代表根目錄,絕對路徑。

在使用相對路徑時,我們用符號“.”來表示當前目錄,用符號“..”來表示當前目錄的父目錄。

一、伺服器內部某位置--->伺服器內部某位置

  • 伺服器內部跳轉,可以使用相對路徑,不加專案名,不加“/”。

案例1.請求轉發,開頭帶不帶/,都可以;

有效request.getRequestDispatcher("error/error404.jsp").forward(request, response);

有效request.getRequestDispatcher("/error/error404.jsp").forward(request, response);

有效request.getRequestDispatcher("/tesyServlet").forward(request, response);

有效request.getRequestDispatcher("tesyServlet").forward(request, response); 

二、客戶端--->伺服器內部某位置

  • 客戶端通過重定向、提交表單、ajax請求、超連結這幾種方式向伺服器傳送請求時,位址列都會顯示相應的地址(位址列有變化),可以斷定這幾種方式殊途同歸,有同樣的路徑格式。
  • 客戶端向伺服器請求資料,為確保路徑不出錯,最好使用絕對路徑。

案例1. 重定向,注:request.getContextPath()=/visit-count

有效response.sendRedirect("tesyServlet");
有效response.sendRedirect("/visit-count/tesyServlet");
有效response.sendRedirect(request.getContextPath()+"/tesyServlet");
有效response.sendRedirect("images/haha.png");
有效response.sendRedirect("error/error404.jsp");
有效response.sendRedirect(request.getContextPath()+"/error/error404.jsp");

無效response.sendRedirect("/tesyServlet");
無效response.sendRedirect("/error/error404.jsp");

案例2.src,包含專案名,則有/;不包含專案名,則無/。注:${APP_PATH }=/visit-count

有效<img alt="圖片" src="images/haha.png">

有效<img alt="圖片" src="${APP_PATH}/images/hahahh.png">

有效<img alt="圖片" src="<%=request.getContextPath()%>/servlet/ImageServlet" />

有效<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script> 

有效<script type="text/javascript" src="${APP_PATH}/js/jquery-2.1.1.min.js"></script>

案例3.href,包含專案名,則有/;不包含專案名,則無/。

有效<a href="error/error404.jsp">error/error404.jsp</a><br>
有效<a href="visitCount">visitCountServlet</a><br>
     
有效<a href="${APP_PATH}/error/error404.jsp">${APP_PATH}/error/error404.jsp</a><br>
有效<a href="${APP_PATH }/visitCountServlet">${APP_PATH }/visitCount</a><br>
有效<a href="/visit-count/visitCountServlet">/visit-count/visitCount</a><br>
     
無效<a href="/visitCount">/visitCountServlet</a><br>
無效<a href="/error/error404.jsp">/error/error404.jsp</a> <br>

三、其他 

 案例1.xml,如下。當error404.jsp顯示到瀏覽器上時,位址列並沒有發生變化,可以推斷這種情況屬於伺服器內部跳轉,用的是相對路徑,卻以“/”開頭,可當成特殊情況來記。

<error-page>
      <error-code>500</error-code>
      有效<location>/error/error404.jsp</location>
       <!-- 錯誤<location>error/error404.jsp</location>
              錯誤<location>/visit-count/error/error404.jsp</location>
              錯誤<location>visit-count/error/error404.jsp</location> -->
</error-page>