Spring MVC-页面重定向示例(转载实践)

以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_page_redirection.htm

说明:示例基于Spring MVC 4.1.6

以下示例显示如何编写一个简单的基于Web的应用程序,该应用程序利用重定向将http请求传输到另一个页面。首先,让我们使用Eclipse IDE,并按照以下步骤使用Spring Web Framework开发基于动态窗体的Web应用程序: 

步骤描述
1 创建一个名为HelloWeb的项目,在一个包com.tutorialspoint下,如Spring MVC - Hello World Example章节所述。
2 在com.tutorialspoint包下创建一个Java类WebController。
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的内容。这将是一个登陆页面,此页面将发送访问重定向服务方法的请求,该方法将将该请求重定向到另一个服务方法,最后将显示一个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>

完成创建源和配置文件后,导出应用程序。右键单击应用程序并使用Export > WAR File选项,并将您的HelloWeb.war文件保存在Tomcat的webapps文件夹中。

现在启动您的Tomcat服务器,并确保您可以使用标准浏览器从webapps文件夹访问其他网页。现在尝试URL http://localhost:8080/HelloWeb/index,如果您的Spring Web应用程序的一切都很好,您应该会看到以下结果:

现在点击“重定向页面”按钮提交表单并获得最终重定向页面。如果您的Spring Web应用程序的一切都很好,您应该会看到以下结果:

Maven示例:

https://github.com/easonjim/5_java_example/tree/master/springmvc/tutorialspoint/test2

posted @ 2017-08-31 22:33  EasonJim  阅读(401)  评论(0编辑  收藏  举报