码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC框架——转发与重定向

时间:2020-03-17 19:39:33      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:发送   mamicode   png   html   技术   response   str   ons   pack   

网上摘取一段大神总结的转发与重定向的区别,如下:

  • 转发(服务端行为)
  1. 形式:request.getRequestDispatcher().forward(request,response)

    转发在服务器端发挥作用,通过forward()方法提交信息在多个页面之间进行传递;

    地址栏不会改变;

    转发只能转发到当前Web应用内的资源;

    在转发过程中,可以将数据保存到 request 域对象中去;

    转发只有一次请求;

    转发是服务器端行为


    2. 转发过程

    客户端浏览器发送http;

    web浏览器接受请求;

    调用内部的一个方法在容器内部完成请求处理和转发动作;


  需注意的是:转发的路径必须是同一个web容器下的url。在客户端浏览器路径栏显示的仍然是第一次访问的路径。转发行为是浏览器只做了一次访问请求。

 

  • 重定向(客户端行为)

  1. 形式:response.sendRedirect("")

    重定向地址栏会改变;

    重定向可以跳转到当前web应用,甚至是外部域名网站;

    不能在重定向的过程中,将数据保存到 request 域对象中;

  2. 重定向过程

    客户端发送http请求;

    web服务器接收后,发送302状态吗响应以及新的location给客户端浏览器;

    客户端浏览器发现是302响应,则自动发送一个http请求,请求url为重定向的地址,响应的服务器根据此请求寻找资源并发送给客户。

示例:

controller

package com.sunjian.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author sunjian
 * @date 2020/3/17 17:53
 */
@Controller
public class TestController {

    /**
     * 重定向
     */
    @RequestMapping(value = "/test1")
    public String testRedirect(){
        return "redirect:test.jsp";
    }

    /**
     * 转发
     */
    @RequestMapping(value = "/test2")
    public String testForward(){
        return "forward:test.jsp";
    }
    @RequestMapping(value = "/test3")
    public String test(){
        return "test";
    }
}

 

JSP

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

 

重定向

  http://localhost:7777/test1  

  技术图片

 

 

转发

  http://localhost:test2

  技术图片

 

 

  http://localhost:test3

  技术图片

 

 

 

 

OK.

SpringMVC框架——转发与重定向

标签:发送   mamicode   png   html   技术   response   str   ons   pack   

原文地址:https://www.cnblogs.com/zuichao123/p/12512655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!