jsp Request獲取url信息的各類方法比較
- 從Request對象中能夠獲取各類路徑信息,如下例子:
- 假設請求的頁面是index.jsp,項目是WebDemo,則在index.jsp中獲取有關request對象的各類路徑信息以下
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- String remoteAddress=request.getRemoteAddr();
- String servletPath=request.getServletPath();
- String realPath=request.getRealPath("/");
- String remoteUser=request.getRemoteUser();
- String requestURI=request.getRequestURI();
- out.println("path:"+path+"<br>");
- out.println("basePath:"+basePath+"<br>");
- out.println("remoteAddr:"+remoteAddress+"<br>");
- out.println("servletPath:"+servletPath+"<br>");
- out.println("realPath:"+realPath+"<br>");
- out.println("remoteUser:"+remoteUser+"<br>");
- out.println("requestURI:"+requestURI+"<br>");
- 結果:
- path:/WebDemo
- basePath:http:
- remoteAddr:127.0.0.1
- servletPath:/index.jsp
- realPath:D:\apache-tomcat-6.0.13\webapps\WebDemo\
- remoteUser:null
- requestURI:/WebDemo/index.jsp
- 從上不難看出request各個對應方法所表明的含義
- 從request獲取各類路徑總結:
- request.getRealPath("url");
- request.getRealPath("./");
- request.getRealPath("../");
- 假定你的web application(web應用)名稱爲news,你的瀏覽器中輸入請求路徑:http:
- request.getContextPath() => /uploading
- request.getServletPath() => /load.jsp
- request.getRequestURL() => http:
- request.getRealPath("/") => F:\learn\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\uploading\
- 如今request.getRealPath("/") 這個方法已經不推薦使用了
- 能夠使用
- ServletContext.getRealPath(java.lang.String) instead.
- request.getSession().getServletContext().getRealPath() 獲得工程文件的實際物理路徑,也就是絕對地址
-
-
- String url = request.getRequestURI();
-
-
- StringBuffer url_buffer = request.getRequestURL();
- HttpServletRequest 的這兩種方法都只能獲得不包含參數的請求url,區別以下:
- 1 前者返回相對路徑,後者返回完整路徑
- 2 前者返回string ,後者返回stringbuffer
- 獲得完整請求url能夠經過以下方法,getQueryString()獲得的是url後面的參數串,和前者相加就是帶參數的請求路徑了
- String queryString = request.getQueryString();
- ring fullPath = url + queryString;
歡迎關注本站公眾號,獲取更多信息