絕對路徑的問題:
1)開發時建議編寫“絕對路徑”:寫絕對路徑肯定沒有問題,但寫相對路徑卻可能會有問題。
在由Servlet轉發到JSP頁面時,此時瀏覽器地址欄上顯示的是Servlet的路徑,而若JSP頁面的超鏈接還是相對於該JSP頁面的地址,則可能會出現路徑混亂的問題
/a.jsp
-path
/b.jsp
/c.jsp
a.jsp->/Servlet -轉發 ->b.jsp(有一個超鏈接:和b.jsp在同一路徑下的c.jsp) ->無法得到頁面
2)編寫絕對路徑可以避免上述問題。
①在JavaWeb中什么叫“絕對路徑”:
相對於當前WEB應用的根路徑的路徑,即任何的路徑都必須帶上contextPath
http://localhost:8081/contextPath(當前WEB應用的上下文路徑)/shopcart/submit.jsp √
http://localhost:8081/a.jsp ×
②如何編寫"絕對路徑":
若/代表站點的根目錄,在其前面加上contextPath就可以了,
而contextPath可以由request或application的getContextPath()方法來獲取
<a href="/TestServlet">To B Page</a> --> <a href="<%= request.getContextPath()%>/TestServlet">To B Page</a>
3)JavaWeb開發中 / 到底代表什么?
①當前WEB應用的根路徑:http://localhost:8081/contextPath/ :若/需交由Servlet容器來處理
>請求轉發時:request.getRequestDispatcher("/path/b.jsp").forward(request,response);
>web.xml文件中映射Servlet訪問路徑:
<servlet>
<servlet-name>Step2Servlet</servlet-name>
<servlet-class>Step2Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Step2Servlet</servlet-name>
<url-pattern>/Step2Servlet</url-pattern>
</servlet-mapping>
②WEB站點的根路徑:http://localhost:8081/ :若/交由瀏覽器來處理
>超鏈接:<a href="/TestServlet">To B Page</a>
>表達中的action:<from action="/login.jsp">
>做請求重定向的時候:response.sendRedirect("/a.jsp");