天天看點

Spring(十八)之頁面重定向

首先說明,該示例的maven依賴可以複用 Spring(十七)之表單處理還有

還有就是對應的web.xml和servlet.xml檔案都能複用,不必再次修改。

說到重定向不得不提到一個轉發。這裡概述一下轉發與重定向的差別:

重定向 和轉發有一個重要的不同:當使用轉發時,JSP容器将使用一個内部的方法來調用目标頁面,新的頁面繼續處理同一個請求,而浏覽器将不會知道這個過程。 與之相反,

方式的含義是第一個頁面通知浏覽器發送一個新的頁面請求。因為,當你使用重定向時,浏覽器中所顯示的URL會變成新頁面的URL, 而當使用轉發時,該URL會保持不變。重定向的速度比轉發慢,因為浏覽器還得發出一個新的請求。同時,由于重定向方式産生了一個新的請求,是以經過一次重 定向後,request内的對象将無法使用。

轉發和重定向的差別

不要僅僅為了把變量傳到下一個頁面而使用session作用域,那會無故增大變量的作用域,轉發也許可以幫助你解決這個問題。

重定向:以前的request中存放的變量全部失效,并進入一個新的request作用域。

轉發:以前的request中存放的變量不會失效,就像把兩個頁面拼到了一起。

比如session的儲存,就是轉發的一個應用執行個體。

Session通過setAttribute以鍵值對的形式儲存Session,而要獲得該session,隻需getAttribute對應的鍵即可,當然了,Session也有它的生命周期,即有效期,超過這個有效期則會發生session失效問題。

通常session有效預設為30分鐘,可以通過web.xml配置修改

<session-config>
    <session-timeout>60</session-timeout>
</session-config>      

一、編寫示例Controller

package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
   @RequestMapping(value = "/index", method = RequestMethod.GET)
   public String index() {
       return "index";
   }   
   @RequestMapping(value = "/redirect", method = RequestMethod.GET)
   public String redirect() {     
      return "redirect:finalPage";
   }   
   @RequestMapping(value = "/finalPage", method = RequestMethod.GET)
   public String finalPage() {     
      return "final";
   }
}      

二、編寫index.jsp和final.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring Page Redirection</title>
</head>
<body>
<h2>Spring Page Redirection</h2>
<p>Click below button to redirect the result to new page</p>
<form:form method="GET" action="/spring-example/redirect">
<table>
    <tr>
    <td>
    <input type="submit" value="Redirect Page"/>
    </td>
    </tr>
</table>  
</form:form>
</body>
</html>      

final.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring Page Redirection</title>
</head>
<body>

<h2>Redirected Page</h2>

</body>
</html>      

三、啟動伺服器,輸入對應的位址

Spring(十八)之頁面重定向

 點選紅色标記處,會出現如圖,這樣就表示正常,否則可能是500,那就是代碼有問題或者環境問題

Spring(十八)之頁面重定向