Web應用中request獲取path,URI,URL


Web應用中有各種獲取path或URI,URL的方法,假設網頁訪問地址:

http://localhost:8080/tradeload/TestServlet

Web應用context: /tradeload 

各路徑鑒定如下:

Java代碼  
  1. request.getContextPath()= /tradeload   
  2. request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()= http://localhost:8080   
  3. request.getRequestURL() = http://localhost:8080/tradeload/TestServlet   
  4. request.getRequestURI() = /tradeload/TestServlet   
  5. request.getPathInfo() = null   
  6. request.getServletPath() = /TestServlet   
  7. getServletContext().getRealPath('/') = C:\server\glassfish\domains\domain1\applications\j2ee-modules\tradeload\   

其中的servletpath就是web.xml中配置的url-pattern。

-------------------------------------------------------------------------------

假定你的web application 名稱為news,你在瀏覽器中輸入請求路徑: 
http://localhost:8080/news/main/list.jsp 

則執行下面向行代碼后打印出如下結果:
1、System.out.println(request.getContextPath());
打印結果:/news
2、System.out.println(request.getServletPath());
打印結果:/main/list.jsp
3、System.out.println(request.getRequestURI());
打印結果:/news/main/list.jsp
4、System.out.println(request.getRealPath("/"));
打印結果:F:\Tomcat 6.0\webapps\news\test

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

out.println("basePath:"+basePath);
out.println("<br/>");
out.println("getContextPath:"+request.getContextPath());
out.println("<br/>");
out.println("getServletPath:"+request.getServletPath());
out.println("<br/>");
out.println("getRequestURI:"+request.getRequestURI());
out.println("<br/>");
out.println("getRequestURL:"+request.getRequestURL());
out.println("<br/>");
out.println("getRealPath:"+request.getRealPath("/"));
out.println("<br/>");
out.println("getServletContext().getRealPath:"+getServletContext().getRealPath("/"));
out.println("<br/>");
out.println("getQueryString:"+request.getQueryString());

 

顯示結果:

basePath:http://localhost:8080/test/

getContextPath:/test
getServletPath:/test.jsp
getRequestURI:/test/test.jsp
getRequestURL:http://localhost:8080/test/test.jsp
getRealPath:D:\Tomcat 6.0\webapps\test\
getServletContext().getRealPath:D:\Tomcat 6.0\webapps\test\
getQueryString:p=fuck

在一些應用中,未登錄用戶請求了必須登錄的資源時,提示用戶登錄,此時要記住用戶訪問的當前頁面的URL,當他登錄成功后根據記住的URL跳回用戶最后訪問的頁面:

String lastAccessUrl = request.getRequestURL() + "?" + request.getQueryString();







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM