天天看點

response.sendRedirect(location)與rd.forward()的差別

HttpServletResponse response = new HttpServletResponse();  
           
response.sendRedirect(location) 

RequestDispatcher rd = new RequestDispatcher();  
rd.forward(request, response) 
           

1. 跳轉方式

 http://localhost:8080/Test應用

運用forward方法隻能重定向到同一個Web應用程式中的一個資源。而sendRedirect方法可以重定向到任何URL。

表單form的action="/uu"; sendRedirect("/uu");表示相對于伺服器根路徑。如http://localhost:8080/Test應用,

則送出至http://localhost:8080/uu

2. 運用RequestDispather接口的forward()方法

forward()無法重定向至有frame的jsp檔案,可以重定向至有frame的html檔案,同時forward()無法在後面帶有參數傳遞,

比如servlet?name=frank,這樣不行,可以在程式内通過request.setAttriibute()來傳至下一個頁面。重定向後,浏覽器位址欄的URL不變

隻有在用戶端沒有輸出時才可以調用forward()方法。如果目前頁面的緩沖區(buffer)不是空的,那麼你在調用forward

方法前必須先清空緩沖區。“/”代表相對與web應用路徑

RequestDispatcher   rd   =   request.getRequestDispatcher( "/ooo "); 

rd.forward(request,   response);送出至http://localhost:8080/Test/ooo 

RequestDispatcher   rd   =   getServletContext().getRequestDispatcher( "/ooo "); 

rd.forward(request,   response);送出至http://localhost:8080/Test/ooo 

RequestDispatcher   rd   =getServletContext().getNamedDispatcher( "TestServlet ");(TestServlet為一個 <servlet-name> ) 

rd.forward(request,   response);送出至名為TestServlet的servlet 

如果在<jsp:forward>之前有很多輸出,前面的輸出已使緩沖區滿,将自動輸出到用戶端,那麼該語句将不起作用。它不能改變浏覽器位址,

重新整理将導緻重複送出。

從http://localhost:8080/Test/gw/page.jsp中轉發 

<jsp:forward   page= "OtherPage.jsp "/> 在JSP頁面被解析後轉換成pageContext.forward( "OtherPage.jsp "); 

"/OtherPage.jsp "送出到http://localhost:8080/Test/OtherPage.jsp 

"OtherPage.jsp "送出到http://localhost:8080/Test/gw/OtherPage.jsp 

3. 運用HttpServletResponse接口的sendRedirect()方法

它在使用者的浏覽器端工作,可以帶參數傳遞,比如servlet?name=frank傳至下個頁面,同時它可以重定向至不同的主機上,

可以重定向有frame的jsp檔案。位址欄将改變

假設轉發代碼包含于注冊的servlet-url為/ggg/tt;   jsp為/ggg/tt.jsp: 

絕對路徑:response.sendRedirect( "http://www.brainysoftware.com ")發送至http://www.brainysoftware.com 

根路徑:response.sendRedirect( "/ooo ")發送至http://localhost:8080/ooo 

相對路徑:response.sendRedirect( "ooo ")發送至http://localhost:8080/Test/ggg/ooo, 

sendRedirect等同于此方式

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); 

String   newLocn   =   "/newpath/jsa.jsp "; 

response.setHeader( "Location ",newLocn); 

4. (Meta   Refresh)方法

這種方法是由html提供的,meta本身是html标簽。使用:<meta http-equiv="refresh" content="5; url=http://www.dreamdu.com/" />

相應的java代碼

String content = stayTime + ";URL=" + URL;

response.setHeader("REFRESH",content);

5. request.setAttribute存的東西

隻有通過RequestDispather接口的forward()方法跳轉,才能在新頁取出來

6. redirect 會首先發一個response給浏覽器,   然後浏覽器收到這個response後再發一個requeset給伺服器,   然後伺服器發新的response給浏覽器.   這時頁面收到的request是一個新從浏覽器發來的.

forward   發生在伺服器内部,   在浏覽器完全不知情的情況下發給了浏覽器另外一個頁面的response.   這時頁面收到的request不是從浏覽器直接發來了,可能己經放了資料.