# 路徑問題
在開發中,我們會出現請求的地方大致包括了以下幾個地方
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");
~~~