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>

 

三、启动服务器,输入对应的地址

 

 点击红色标记处,会出现如图,这样就表示正常,否则可能是500,那就是代码有问题或者环境问题

 

posted @ 2018-08-12 12:59  挑战者V  阅读(742)  评论(0编辑  收藏  举报