以下示例显示如何编写基于Web的简单应用程序,该应用程序使用重定向将http请求传输到另一个页面.首先,让我们使用一个可用的Eclipse IDE并考虑以下步骤,使用Spring Web Framework开发基于动态表单的Web应用程序 :
Step | 描述 |
---|---|
1 | 在com.it1352包下创建一个名为HelloWeb的项目,如Spring所述MVC - Hello World章节. |
2 | 创建com.it1352包下的Java类WebController. |
3 | 在jsp子文件夹下创建视图文件index.jsp,final.jsp. |
4 | 最后一步是创建源文件和配置文件的内容并导出应用程序,如下所述. |
package com.it1352; 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 页面.
<%@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>
<%@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>
完成创建源文件和配置文件后,导出应用程序.右键单击您的应用程序,使用Export → WAR文件选项并将您的HelloWeb.war文件保存在Tomcat的webapps文件夹中.
现在,启动Tomcat服务器并确保您能够使用标准浏览器从webapps文件夹访问其他网页.尝试使用URL -http://localhost:8080/HelloWeb/index,如果Spring Web Application的一切正常,你应该看到以下屏幕.
现在点击"重定向页面"按钮提交表单并进入最终重定向页面.我们应该看到以下屏幕,如果一切正常,我们的Spring Web Application :