在開發網站時候我們會遇到下面問題?
- - 在引用網頁中引用js和css或者動態的Servlet的時候我們是寫絕對路徑還是相對路徑?
- - 如果寫相對路徑吧,上線偶爾會報404,還要手動去拼接絕對路徑
- - 如果寫絕對路徑吧,你在本地寫的時候肯定的是localhost:8080/xxx/xxx,項目上線的時候你又要把網頁中的這個替換為你的上線域名,體驗很糟糕
我們怎么解決這樣的問題呢?
我們可以在網頁中使用Request對象來獲取網頁中的各種地址信息。
- request.getServletPath(); 獲取當前網頁的地址 - request.getScheme(); 獲取協議 - request.getServerName(); 獲取域名 - request.getServerPort(); 獲取端口號 - request.getContextPath(); 獲取項目名稱
下面我們來拼接成一個通用的獲取項目地址的變量,讓在jsp網頁中隨處都可以使用它啦
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
獲取到的就是下面這樣的地址
basePath:http://localhost:8080/WebDemo/
我們可以在jsp頁面寫入下面代碼
<% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %>
在引用Js和css或者需要拼接路徑的時候我們可以直接使用basePath這個變量,例如
<link rel="stylesheet" href="<%=basePath %>resources/assets/css/font-xxx.min.css" /> <link rel="stylesheet" href="<%=basePath %>resources/assets/css/xxx.min.css" /> <link rel="stylesheet" href="<%=basePath %>resources/assets/css/xxx.min.css" />
當然我們每一次都需要在jsp文件編寫下面的代碼嗎?那可真的是太復雜了,我們可以直接在web.xml中稍微配置一下,就可以啦,下面看看怎么來操作。
- 創建一個commons.jsp文件,文件寫入下面代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
- 在web.xml進行配置,使所有的jsp網頁都能自動的引用commons.jsp這個網頁(ps:引入這個網頁當然就能使用basePath這個變量嘍~~直接就能使用啦)
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<include-prelude>/commons.jsp</include-prelude>
</jsp-property-group>
</jsp-config>
注意:<include-prelude>/commons.jsp</include-prelude>標簽中的jsp文件改成你的commons.jsp文件的存放地址
不適用這種方案的情況
- 前后端分離的項目 - Html網頁中 - 。。。