一、請求轉發與響應重定向的種類
有兩種方式獲得servlet 轉發對象(requestdispatcher):一種是通過httpservletrequest的getrequestdispatcher()方法獲得,一種是通過servletcontext的getrequestdispatcher()方法獲
得。
servlet 重定向的方法隻有一種:httpservletresponse的sendredirect()方法。
這三個方法的參數都是一個url形式的字元串,但在使用相對路徑或絕對路徑上有所差別。
二、請求轉發與響應重定向中路徑參數差別
假設通過http://localhost/myapp/cool/bar.do 請求到達該方法所屬的servlet。
1、響應重定向 ◆ httpservletresponse.sendredirect(string)
參數可以指定為相對路徑、絕對路徑或其它web應用。
i:相對路徑:response.sendredirect("foo/stuff.do"),容器相對于原來請求url的目錄加參數來生成完整的url——http://localhost/myapp/cool/foo/stuff.do。
ii:絕對路徑:response.sendredirect("/foo/stuff.do"),容器相對于web應用本身加參數建立完整的url,這是因為 重定向response.sendredirect("")是伺服器向用戶端發送一個請求頭資訊,由用戶端再請求一次伺服器,請求是在伺服器外進行的,即完整的url是——http://localhost/foo/stuff.do。
iii:其它web應用:response.sendredirect("http://www.xxx.com ")容器直接定向到該url。
2、請求轉發 ◆httpservletrequest.getrequestdispatcher(string)
參數可以指定為相對路徑或絕對路徑。
i:相對路徑情況下生成的完整url與重定向方法相同。
ii:絕對路徑與servlet重定向不同,容器将相對于web應用的根目錄加參數生成完整的url(即“/”根路徑就是相對于虛拟路徑)這是因為轉發是在伺服器内部進行的,寫絕對路徑/開頭指的是目前的web應用程式
。即:
request.getrequestdispatcher("/foo/stuff.do")生成的url是http://localhost/myapp/foo/stuff.do
。
3、 ◆ servletcontext.getrequestdispatcher(string)
參數隻能指定為絕對路徑,生成的完整url與httpservletrequest.getrequestdispatcher(string)相同。
##################################
同理:
jsp頁面送出表單給servlet時,路徑的寫法要格外注意。
例如在web.xml中注冊如下的servlet:
<servlet>
<servlet-name>addstudent</servlet-name>
<servlet-class>org.mytest.addstudent</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern>/servlet/addstudent</url-pattern>
</servlet-mapping>
假如說,你工程名字為hibernateapp3,jsp頁面送出表單給servlet時有兩種寫法:
1.相對路徑: <form action=servlet/addstudent method=post>...</form>
2. 絕對路徑: <form action="/hibernateapp3/servlet/addstudent" method=post>...</form>
或者 <form action="<%=request.getcontextpath() %>/servlet/addstudent" method=post>...</form>
注意:/代表根目錄,如果路徑是使用/開頭,tomcat就是webapp那個目錄,如果你不是/開頭代表你從目前工程的目錄開始,例如:webapp/hibernateapp3/
這一點非常重要,很多送出表單時發生的錯誤都是因為送出路徑出錯造成的。
附、<a href>的路徑如果是"/"開頭,則表示相對于主機,如果不是則表示相對于目前請求
綜上所述:這裡最最關鍵的要能清楚送出請求目的資源的請求是在伺服器内部還是伺服器外部:内部時,“/”就是項目的虛拟目錄;外部時,“/”就是代表主機的根目錄