在java web種經(jīng)常出現(xiàn) 404找不到網(wǎng)頁(yè)的錯(cuò)誤,究其原因,一般是訪問(wèn)的路徑不對(duì)。
java web中的路徑使用按我的分法可以分兩種情況,當(dāng)然啦兩者使用相對(duì)路徑是一致,本文只說(shuō)絕對(duì)路徑。
情況一、指向外部的web組件和本身關(guān)系不大的,這一類(lèi)的有:html中使用路徑的標(biāo)簽,比如<a>標(biāo)簽中的href;servlet和jsp中的重定向sendRedirect(path);
情況二、指向內(nèi)部的web組件和本身有關(guān)系的,這一類(lèi)我暫時(shí)看到的有:servlet或者jsp的轉(zhuǎn)發(fā)
假設(shè)在myapp項(xiàng)目下有個(gè)login.html,index.jsp,還寫(xiě)了兩個(gè)servletA和servletB.
在web.xml中的地址配置:
<url-pattern>/servlet/servletA</url-pattern>
<url-pattern>/servlet/servletB</url-pattern>
在情況一中:若在路徑中以/開(kāi)頭,則這一/相當(dāng)于http://localhost:8080/
1、login.html有個(gè)form表單有提交給servletA,那么action要填的路徑:
絕對(duì)路徑方式:action="/myapp/servlet/servletA" ------http://localhost:8080/myapp/servlet/servletA
相對(duì)路徑方式:action="servlet/servletA" ------http://localhost:8080/myapp/servlet/servletA
2、login.html有個(gè)<a>鏈接到index.jsp 那么
絕對(duì)路徑方式:href="/myapp/index.jsp" ------http://localhost:8080/myapp/index.jsp
相對(duì)路徑方式:action="index.jsp" ------http://localhost:8080/myapp/index.jsp
3、index.jsp中重定向到servletA
絕對(duì)路徑方式:sendRedirect("/myapp/servlet/servletA"); ------http://localhost:8080/myapp/servlet/servletA
相對(duì)路徑方式:sendRedirect("servlet/servletA"); ---http://localhost:8080/myapp/servlet/servletA
在情況二中:若在路徑中以/開(kāi)頭,則這一/相當(dāng)于http://localhost:8080/myapp/
1.servletA轉(zhuǎn)發(fā)到servletB
絕對(duì)路徑方式:request.getRequestDispatcher("/servlet/servletB").forward(request, response);
--------http://localhost:8080/myapp/servlet/servletB
相對(duì)路徑方式:request.getRequestDispatcher("servlet/servletB").forward(request, response);
--------http://localhost:8080/myapp/servlet/servletB
注意:
建議使用絕對(duì)路徑,相對(duì)路徑是相對(duì)于當(dāng)前瀏覽器地址欄的路徑(源地址)。
可能會(huì)出現(xiàn):你在某個(gè)頁(yè)面寫(xiě)了一個(gè)相對(duì)路徑(目標(biāo)路徑),因?yàn)檗D(zhuǎn)發(fā)是不改變地址的,那么要是別人是通過(guò)轉(zhuǎn)發(fā)到達(dá)你的這個(gè)頁(yè)面的,那么地址欄的源地址就是不確定的,既然不確定你使用相對(duì)路徑相對(duì)于這個(gè)不確定的路徑就極有可能出錯(cuò),所以建議使用絕對(duì)路徑,這樣可避免這種問(wèn)題。
獲得項(xiàng)目路徑和絕對(duì)路徑:
項(xiàng)目路徑:String path=request.getContextPath(); ---- /myapp
String p=this.getServletContext().getRealPath("/"); ----- G:\environment\tomcat\webapps\myapp\
總結(jié):
這里主要弄明白是指向外部的還內(nèi)部的,外部時(shí)"/"就是代表主機(jī)路徑,內(nèi)部時(shí)"/"就是代表當(dāng)前項(xiàng)目路徑.
聯(lián)系客服