1 從Request對象中可以獲取各種路徑信息,以下例子: 2 假設請求的頁面是index.jsp,項目是WebDemo,則在index.jsp中獲取有關request對象的各種路徑信息如下 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 String remoteAddress=request.getRemoteAddr(); 6 String servletPath=request.getServletPath(); 7 String realPath=request.getRealPath("/"); 8 String remoteUser=request.getRemoteUser(); 9 String requestURI=request.getRequestURI(); 10 out.println("path:"+path+"<br>"); 11 out.println("basePath:"+basePath+"<br>"); 12 out.println("remoteAddr:"+remoteAddress+"<br>"); 13 out.println("servletPath:"+servletPath+"<br>"); 14 out.println("realPath:"+realPath+"<br>"); 15 out.println("remoteUser:"+remoteUser+"<br>"); 16 out.println("requestURI:"+requestURI+"<br>"); 17 結果: 18 path:/WebDemo 19 basePath:http://localhost:8683/WebDemo/ 20 remoteAddr:127.0.0.1 21 servletPath:/index.jsp 22 realPath:D:\apache-tomcat-6.0.13\webapps\WebDemo\ 23 remoteUser:null 24 requestURI:/WebDemo/index.jsp 25 從上不難看出request各個對應方法所代表的含義
1 從request獲取各種路徑總結: 2 request.getRealPath("url");//虛擬目錄映射為實際目錄 3 request.getRealPath("./");//網頁所在的目錄 4 request.getRealPath("../");//網頁所在目錄的上一層目錄 5 假定你的web application(web應用)名稱為news,你的瀏覽器中輸入請求路徑:http://localhost:8080/uploading/load.jsp 6 request.getContextPath() => /uploading 7 request.getServletPath() => /load.jsp 8 request.getRequestURL() => http://localhost:8080/uploading/load.jsp 9 request.getRealPath("/") => F:\learn\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\uploading\ 10 現在request.getRealPath("/") 這個方法已經不推薦使用了 11 可以使用 12 ServletContext.getRealPath(java.lang.String) instead. 13 request.getSession().getServletContext().getRealPath() 得到工程文件的實際物理路徑,也就是絕對地址
//Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request // eg. /manage/editExam.domethod=goExamSet&type=U String url = request.getRequestURI(); //The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters //eg. http://127.0.0.1:8080/manage/editExam.domethod=goExamSet&type=U StringBuffer url_buffer = request.getRequestURL(); HttpServletRequest 的這兩種方法都只能得到不包含參數的請求url,區別如下: 1 前者返回相對路徑,后者返回完整路徑 2 前者返回string ,后者返回stringbuffer 得到完整請求url可以通過如下方法,getQueryString()得到的是url后面的參數串,和前者相加就是帶參數的請求路徑了 String queryString = request.getQueryString(); ring fullPath = url + queryString; // 或者是url_buffer.toString()+queryString;