使用相對路徑可能會有問題, 但使用絕對路徑肯定沒有問題.
1). 絕對路徑: 相對于目前 WEB 應用的路徑. 在目前 WEB 應用的所有的路徑前都添加 contextPath 即可.
2). / 什麼時候代表站點的根目錄, 什麼時候代表目前 WEB 應用的根目錄
若 / 需要伺服器進行内部解析, 則代表的就是 WEB 應用的根目錄. 若是交給浏覽器了, 則 / 代表的就是站點的根目錄
若 / 代表的是 WEB 應用的根目錄, 就不需要加上 contextPath 了。
2. 相對路徑和絕對路徑:
1). 為什麼要解決相對路徑的問題: 在有一個 Servlet 轉發頁面的情況下, 會導緻相對路徑的混亂.
a.jsp: <a href="ToBServlet" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >To B Page2</a>
ToBServlet: request.getRequestDispatcher("/dir/b.jsp").forward(request, response);
注意, 此時點選 To B Page2 超連結後的浏覽器的位址欄的值: http://localhost:8989/testpro/ToBServlet, 實際顯示的是
dir 路徑下的 b.jsp,而 b.jsp 頁面有一個超連結: <a href="c.jsp" target="_blank" rel="external nofollow" >TO C Page</a>. 預設情況下, c.jsp 應該和 b.jsp 在同一路徑下. 此時點選超連結
将在浏覽器位址欄顯示: http://localhost:8989/testpro/c.jsp. 但在根目錄下并沒有 c.jsp, 是以會出現路徑混亂的問題.
2). 使用絕對路徑會解決以上的問題:
絕對路徑: 相對于目前 WEB 站點根目錄的路徑.
http://localhost:8989/testpro/c.jsp:
http://localhost:8989/ 是 WEB 站點的根目錄, /testpro 是 contextPath,
/c.jsp 是相對于目前 WEB 應用的一個檔案路徑. 我們需要在目前 WEB 應用的任何的路徑下都添加上 contextPath, 即可.
比如:
<a href="ToBServlet" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >To B Page2</a> 需改為: <a href="<%= request.getContextPath() %>/ToBServlet" target="_blank" rel="external nofollow" >To B Page2</a>
response.sendRedirect("a.jsp"); 需改為: response.sendRedirect(request.getContextPath() + "/a.jsp");
<form action="AddServlet"></form> 需改為: <form action="<%= request.getContextPath() %>/AddServlet"></form>
3). 在 JavaWEB 應用中 / 代表的是: 有時代表目前 WEB 應用的根目錄, 有時代表的是站點的根目錄.
/ 代表的是目前 WEB 應用的根路徑: 若 / 所在的指令或方法需被 WEB 伺服器解析, 而不是直接打給浏覽器, 則 / 代表 WEB 應用的根路徑. 此時編寫
絕對路徑就不需要在添加 contextPath 了.
在 web.xml 檔案中做 Serlvet 映射路徑時,
在請求轉發: request.getRequestDispatcher("/dir/b.jsp").forward(request, response);
/ 代表的是站點的根目錄: 若 / 直接交由浏覽器解析, / 代表的就是站點的根路徑, 此時必須加上 contextPath
<form action="/AddServlet"></form>
response.sendRedirect("/a.jsp");
4). 如何擷取 contextPath:
ServletContext: getContextPath()
HttpServletRequest: getContextPath()