新聞中心
Spring 頁面重定向例子
下面的例子說明了如何編寫一個簡單的基于 web 的應(yīng)用程序,它利用重定向來傳送一個 http 請求到另一個頁面中。為了開始使用它,讓我們在恰當(dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟使用 Spring 的 Web 框架來開發(fā)一個動態(tài)的基于表單的 Web 應(yīng)用程序:

| 步驟 | 描述 |
|---|---|
| 1 | 創(chuàng)建一個名稱為 HelloWeb 的動態(tài) Web 項(xiàng)目,并且在已創(chuàng)建的項(xiàng)目的 src 文件夾中創(chuàng)建一個包 com.tutorialspoint。 |
| 2 | 將上面提到的 Spring 和其他庫拖拽到文件夾 WebContent/WEB-INF/lib 中。 |
| 3 | 在 com.tutorialspoint 包下創(chuàng)建一個 Java 類 WebController。 |
| 4 | 在 WebContent/WEB-INF 文件夾下創(chuàng)建 Spring 的配置文件 Web.xml 和 HelloWeb-servlet.xml。 |
| 5 | 在 WebContent/WEB-INF 文件夾下創(chuàng)建名稱為 jsp 的子文件夾。在這個子文件夾下創(chuàng)建視圖文件 index.jsp 和 final.jsp。 |
| 6 | 最后一步是創(chuàng)建所有的源代碼和配置文件的內(nèi)容,并導(dǎo)出該應(yīng)用程序,正如下面解釋的一樣。 |
這里是 WebController.java 文件的內(nèi)容:
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 Web 配置文件 web.xml 的內(nèi)容
Spring Page Redirection
HelloWeb
org.springframework.web.servlet.DispatcherServlet
1
HelloWeb
/
下面是另一個 Spring Web 配置文件 HelloWeb-servlet.xml 的內(nèi)容
下面是 Spring 視圖文件 index.jsp 文件的內(nèi)容。這將是一個登陸頁面,這個頁面將發(fā)送一個請求來訪問重定向 service 方法,該方法將把這個請求重定向到另一個 service 方法中,最后將顯示 final.jsp 頁面。
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
Spring Page Redirection
Spring Page Redirection
Click below button to redirect the result to new page
下面是 Spring 視圖文件 final.jsp 的內(nèi)容。這是最終的重定向頁面。
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
Spring Page Redirection
Redirected Page
最后,下面是包含在你的 web 應(yīng)用程序中的 Spring 和其他庫的列表。你僅僅需要將這些文件拖拽到 WebContent/WEB-INF/lib 文件夾中。
-
commons-logging-x.y.z.jar
-
org.springframework.asm-x.y.z.jar
-
org.springframework.beans-x.y.z.jar
-
org.springframework.context-x.y.z.jar
-
org.springframework.core-x.y.z.jar
-
org.springframework.expression-x.y.z.jar
-
org.springframework.web.servlet-x.y.z.jar
-
org.springframework.web-x.y.z.jar
- spring-web.jar
一旦你完成了創(chuàng)建源代碼和配置文件后,導(dǎo)出你的應(yīng)用程序。右鍵單擊你的應(yīng)用程序,并且使用 Export > WAR File 選項(xiàng),并且在 Tomcat 的 webapps 文件夾中保存你的 HelloWeb.war 文件。
現(xiàn)在啟動你的 Tomcat 服務(wù)器,并且確保你能夠使用標(biāo)準(zhǔn)的瀏覽器訪問 webapps 文件夾中的其他 web 頁面?,F(xiàn)在嘗試訪問該 URL http://localhost:8080/HelloWeb/index。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:
現(xiàn)在單擊 “Redirect Page” 按鈕來提交表單,并且得到最終的重定向頁面。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:
新聞標(biāo)題:創(chuàng)新互聯(lián)Spring教程:Spring頁面重定向例子
網(wǎng)頁地址:http://www.dlmjj.cn/article/cdehhcc.html


咨詢
建站咨詢
