獲取服務器的路徑(即Java後臺代碼)html
String path = request.getSession().getServletContext().getRealPath("/upload");web
結果顯示爲:D:\\apache-tomcat-7.0.42\\webapps\\OA\\uploadapache
2.在jsp上獲取路徑瀏覽器
String path = request.getContextPath();tomcat
request.getContextPath()應該是獲得項目的名字,若是項目爲根目錄,則獲得一個"",即空的字條串。若是項目爲abc,服務器
<%=request.getContextPath()% > 將獲得abc,服務器端的路徑則會自動加上,<a href="XXXX.jsp"> 是指當前路徑下的這個app
xxx.jsp頁面,有時候也能夠在head裏設置html:base來解決路徑的問題,不過用的最多的仍是request.getContextPathwebapp
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";jsp
request.getScheme();
返回的協議名稱,默認是httpspa
request.getServerName()
返回的是你瀏覽器中顯示的主機名,你本身試一下就知道了
getServerPort()
獲取服務器端口號
假定你的web application 名稱爲news,你在瀏覽器中輸入請求路徑:
http://localhost:8080/news/main/list.jsp
則執行下面向行代碼後打印出以下結果:
一、 System.out.println(request.getContextPath());
打印結果:/news
二、System.out.println(request.getServletPath());
打印結果:/main/list.jsp
三、 System.out.println(request.getRequestURI());
打印結果:/news/main/list.jsp
四、 System.out.println(request.getRealPath("/"));
打印結果:F:\Tomcat 6.0\webapps\news\test
例如: http://localhost:80/myblog/authen/login.do
request.getSchema()能夠返回當前頁面使用的協議,就是上面例子中的「http」
request.getServerName()能夠返回當前頁面所在的服務器的名字,就是上面例子中的「localhost"
request.getServerPort()能夠返回當前頁面所在的服務器使用的端口,就是80,
request.getContextPath()能夠返回當前頁面所在的應用(工程或者項目)的名字,就是上面例子中的myblog
這四個拼裝起來,就是當前應用的根路徑了
String path = request.getContextPath(); //獲得的是我要訪問的項目名:MAOA
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.getScheme()//獲得的是:http
request.getServerName()//獲得的是主機名。也就是我要訪問的項目的ip,若是是在個人電腦上那麼,獲得的就是localhost
request.getServerPort();//獲得的是我要訪問問項目的服務器端口號,
path;就是上面的獲得的項目名MAOA