# 路徑問題
在開發中,我們會出現請求的地方大致包括了以下幾個地方
1. 在 HTML 頁面通過 A 標簽請求;
2. 在 JS 中的 AJAX 請求;
3. 在 Servlet 中通過 `response.sendRedirect(url)` 重定向;
4. 在 Servlet 中通過`request.getRequestDispatcher(url).forward(request, response)` 轉發。
在實際的應用中,1/2/3 建議使用絕對路徑去完成,4 通過相對路徑完成。
所謂絕對路徑就是請求的地址用完整的路徑去表現,例如 `http://localhost:8080/demo1/loginServlet.do`
## 如果使用絕對路徑
獲取絕對路徑:
~~~
String path = request.getContextPath(); // 獲取應用上下文,即在 server.xml 中定義的 path
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// request.getScheme():獲取協議 http
// request.getServerName():獲取協議服務器
// request.getServerPort():獲取端口號
// 上述定義的 basePath 就是請求的地址的完整前綴
~~~
> 在開發中,我可以將 basePath 變量定義在 request 變量中,然后在需要的地方(如 jsp 中)通過 `request.getAttribute("bath")` 或者 EL `${basePath} `方式獲取。
> 為了避免每個 Servlet 中都要定義 basePath,我們可以在過濾器中定義 basePath。
~~~
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
HttpServletRequest req = (HttpServletRequest) request;
req.setCharacterEncoding(encoding);
String path = req.getContextPath();
String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"";
req.setAttribute("path", basePath);
// pass the request along the filter chain
chain.doFilter(request, response);
}
~~~
**在 JSP 中使用**
~~~
<script src="${path}/assets/js/jquery-3.2.1.min.js"></script>
$.ajax({
url : "${path}/admin/UpdateForwardAjaxServlet.do",
async:false,
dataType : "json",
data : toData,
success : function(data) {
$("#editStuId").val(data.id);
$("#editStuName").val(data.name);
$("#editStuCode").val(data.code);
}
});
~~~
在 Servlet 或者 過濾器中使用
~~~
String path = req.getContextPath();
String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"";
res.sendRedirect(basePath + "/common/LoginServlet.do?error=LOGIN_ERROR_02");
~~~
- 前言
- 計算機概論
- 數據庫
- 數據庫介紹
- MySQL的安裝
- SQL
- 表基本操作
- 修改數據語句
- 數據檢索操作
- 多表數據操作
- 表結構設計
- 綜合應用
- JAVA
- JAVA 介紹
- JAVA 運行原理
- JDK 配置
- 類和對象
- 數據類型
- 變量
- 直接量
- 運算符
- 流程控制
- 數組結構
- 面向對象
- 隱藏和封裝
- 深入構造器
- 類的繼承
- 多態
- 包裝類
- final 修飾符
- 抽象類
- 接口
- 集合框架
- 常用類學習
- 異常處理
- 設計模式-單例模式
- JDBC
- JSP&Servlet
- Web應用
- Tomcat
- JSP
- Scriptlet
- Page 指令
- 包含指令
- 跳轉指令
- 用戶注冊實例
- JSP練習
- 內置對象
- Servlet
- 過濾器
- Web分層思想
- EL表達式
- JSTL
- 分頁實現
- AJAX&JSON
- 開發步驟
- 路徑問題
- Log4j
- 電子書城
- 案例分析
- 核心代碼
- Java 高級
- 文件操作
- 泛型
- 類加載機制和反射
- 注解 Annotation
- Mybatis框架
- 框架介紹
- Mybatis簡單實現
- 表基本操作
- 優化配置文件
- 表字段名與實體類屬性名不同的解決方案
- 一對一關聯
- 一對多關聯
- 教學管理
- 學員名錄
- 周測統計
- 2017-10-27
- 2017-11-03
- 2017-11-10
- 2017-11-17
- 課堂作業
- 班會紀要
- 2017-10-24
- 缺勤記錄
- 班級備忘錄
- 違紀統計
- 編程素養
- Day001
- Day002
- Day003
- Day004
- Day005
- Day006
- Day007
- Day008
- Day009
- Day010
- Day011
- Day012
- Day013
- Day014
- Day015
- Day016
- Day017
- Day018
- Day019