web中src引用檔案的路徑問題

來源:互聯網
上載者:User

標籤:cal   get   attribute   不能   相對路徑   lan   結構   java   通過   

在編寫web應用的時候,難免會在一個檔案中引用外部的檔案,例如樣式表css檔案以及一些指令碼js檔案,這樣做的目的無疑是提高代碼的複用率。但是在引用檔案時,一定要引用正確的檔案路徑,不然是訪問不到相關檔案的。

總結一下,一共有如下幾種方式引用相關檔案:

前提:

相關目錄結構:

方法一:使用相對於當前檔案(源檔案)的相對路徑

 

[html] view plain copy print?
  1. <link type="text/css" rel="stylesheet" href="../styles/main.css" />    
  2. <script type="text/javascript" src="../scripts/dtree.js"></script>    
<link type="text/css" rel="stylesheet" href="../styles/main.css" />  <script type="text/javascript" src="../scripts/dtree.js"></script>  

這樣在頁面使用http://localhost:8080/MyProject/test.jsp訪問test.jsp時就可以引用到dtree.js和main.css。

 

方法二:使用相對於web工程的相對路徑

 

[html] view plain copy print?
  1. <link type="text/css" rel="stylesheet" href="styles/main.css" />    
  2. <script type="text/javascript" src="scripts/dtree.js"></script>    
<link type="text/css" rel="stylesheet" href="styles/main.css" />  <script type="text/javascript" src="scripts/dtree.js"></script>  

但是如上兩種方法都有其瓶頸,對於方法一中的相對使用相對于于jsp頁面的相對路徑的這種方式,如果我們是設定action跳轉到test.jsp頁面,那麼這種使用相對路徑的方式就引用不到了。例如我們當訪問http://localhost:8080/MyProject/main.do的時候,頁面跳轉到test.jsp頁面,如果使用方法1,就引用不到了。如果使用方法2這種方式引用,如果直接存取http://localhost:8080/MyProject/test.jsp,是引用不到的。

 

那麼有沒有一種兩全其美的方法呢,答案是肯定的,也就是我們的方法三:使用web工程的絕對路徑

 

[html] view plain copy print?
  1. <link type="text/css" rel="stylesheet" href="/MyProject/styles/main.css" />    
  2. <script type="text/javascript" src="/MyProject/scripts/dtree.js"></script>    
<link type="text/css" rel="stylesheet" href="/MyProject/styles/main.css" />  <script type="text/javascript" src="/MyProject/scripts/dtree.js"></script>  

這樣,不管是通過http://localhost:8080/MyProject/main.do跳轉訪問test.jsp還是直接存取http://localhost:8080/MyProject/test.jsp,都可以成功引用。 注意:如果我們在部署Web應用時,沒有設定Context Root(一般情況下配置為工程名),也就是IP和端口後面不帶應用程式名稱,如http://localhost:8080/main.do和http://localhost:8080/test.jsp,這種情況在引用時就不能帶工程名了,應該這樣:

 

 

[html] view plain copy print?
  1. <link type="text/css" rel="stylesheet" href="/styles/main.css" />    
  2. <script type="text/javascript" src="/scripts/dtree.js"></script>    
<link type="text/css" rel="stylesheet" href="/styles/main.css" />  <script type="text/javascript" src="/scripts/dtree.js"></script>  

web中src引用檔案的路徑問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.