Spring MVC - 頁面重定向示例



以下示例演示如何編寫一個簡單的基於 Web 的應用程式,該應用程式使用重定向將 HTTP 請求傳輸到另一個頁面。首先,讓我們準備好一個可用的 Eclipse IDE,並考慮以下步驟來使用 Spring Web 框架開發基於動態表單的 Web 應用程式:

步驟 描述
1 建立一個名為 HelloWeb 的專案,位於 com.tutorialspoint 包下,如 Spring MVC - Hello World 章節中所述。
2 在 com.tutorialspoint 包下建立一個名為 WebController 的 Java 類。
3 在 jsp 子資料夾下建立檢視檔案 index.jsp 和 final.jsp。
4 最後一步是建立原始檔和配置檔案的內容,並匯出應用程式,如下所述。

WebController.java

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";
   }
}

以下是 Spring 檢視檔案 **index.jsp** 的內容。這將是一個登入頁面,此頁面將向 access-redirect 服務方法傳送請求,該方法將此請求重定向到另一個服務方法,最終將顯示 **final.jsp** 頁面。

index.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 = "/HelloWeb/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>

建立完原始檔和配置檔案後,匯出您的應用程式。右鍵單擊您的應用程式,使用匯出 → WAR 檔案選項,並將您的 HelloWeb.war 檔案儲存到 Tomcat 的 webapps 資料夾中。

現在,啟動您的 Tomcat 伺服器,並確保您可以使用標準瀏覽器訪問 webapps 資料夾中的其他網頁。嘗試使用 URL –https://:8080/HelloWeb/index,如果 Spring Web 應用程式一切正常,您應該會看到以下螢幕。

Spring Redirect Form

現在,單擊“重定向頁面”按鈕提交表單,以轉到最終重定向的頁面。如果我們的 Spring Web 應用程式一切正常,我們應該會看到以下螢幕:

Spring Redirect Form Result
廣告