getContextPath、getServletPath、getRequestURI的區別


假定你的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 

結合到Spring MVC項目來說一下:

1.jsp:           

 <li><a class="add" rel="add-category" href="${ctx}/admin/category/create.do?parentId=${param.q_eq_parentId}" target="navTab" title="添加目錄"><span>添加</span></a></li>

2.如何找到${ctx}/admin/category/create.do地址?

首先,找ctx代表什么。假如:pageContext.setAttribute("ctx", application.getContextPath());從上面的解說可以知道System.out.println(request.getContextPath())得出的是/news。故完整路徑為:/news/admin/category/create.do。至於參數則根據實際研究。

可看到上路徑為.do結尾。Spring MVC與Struts從原理上很相似(都是基於MVC架構),都有一個控制頁面請求的Servlet,處理完后跳轉頁面。spring會自動掃描找到該路徑對應的controller,如下圖所示:

 

當前對應的路徑為CategoryController類下的showCreate方法

 

 

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

 

輸出:

path:/E_WuLiu
basePath:http://localhost:8080/E_WuLiu/

getContextPath():得到當前應用的根目錄

getScheme():它返回當前請求所使用的協議。 一般的應用返回 "http",對於ssl則返回"https"

getServerName():獲取服務器名字,如果是在本地的話就是localhost

getServerPort():獲得服務器的端口號

 

 

另外:jsp中獲取客戶端的瀏覽器和操作系統信息

string agent = request.getheader("user-agent");
stringtokenizer st = new stringtokenizer(agent,";");
st.nexttoken();
//得到用戶的瀏覽器名
string userbrowser = st.nexttoken();
//得到用戶的操作系統名
string useros = st.nexttoken();

 

取得本機的信息也可以這樣:

 

操作系統信息
system.getproperty("os.name"); //win2003竟然是win xp?
system.getproperty("os.version");
system.getproperty("os.arch");


瀏覽器:
request.getheader("user-agent")

 

其他
request.getheader(“user-agent”)返回客戶端瀏覽器的版本號、類型

getheader(string name):獲得http協議定義的傳送文件頭信息,

request. getmethod():獲得客戶端向服務器端傳送數據的方法有get、post、put等類型

request. getrequesturi():獲得發出請求字符串的客戶端地址

request. getservletpath():獲得客戶端所請求的腳本文件的文件路徑

request. getservername():獲得服務器的名字

request.getserverport():獲得服務器的端口號

request.getremoteaddr():獲得客戶端的ip地址

request.getremotehost():獲得客戶端電腦的名字,若失敗,則返回客戶端電腦的ip地址

request.getprotocol():

request.getheadernames():返回所有request header的名字,結果集是一個enumeration(枚舉)類的實例

request.getheaders(string name):返回指定名字的request header的所有值,結果集是一個enumeration(枚舉)類的實例


免責聲明!

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



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