Spring MVC 重定向和转发

Spring MVC 重定向和转发

1.请求转发和重定向的区别:

  请求重定向和请求转发都是web开发中资源跳转的方式。

  请求转发是服务器内部的跳转

    地址栏不发生变化

    只有一个请求响应

    可以通过request域传递数据

  请求重定向是浏览器自动发起对跳转目标的请求

    地址栏会发生变化

    两次请求响应

    无法通过request域传递对象

 2.SpringMVC实现转发和重定向:

在有视图解析器的情况下默认就是转发,需要重定向直接redirect:就行了

/**
     * 实现转发
     * @throws Exception 
     */
    @RequestMapping("/hello11.action")
    public String hello11(HttpServletRequest request) throws IOException, Exception{
        request.setAttribute("name", "zsf");
        return "hello";
    }
    
    /**
     * 实现重定向
     * @throws Exception 
     */
    @RequestMapping("/hello12.action")
    public String hello12(HttpServletRequest request) throws IOException, Exception{
        request.setAttribute("name", "zsf");
        return "redirect:/hello.action";
    }

请求转发示意图:

在这里插入图片描述

重定向示意图:

原文地址:https://www.cnblogs.com/love2000/p/14275624.html