Springmvc的转发和重定向

1.什么是转发?什么是重定向

在Servlet中实现页面的跳转有两种方式:转发和重定向

什么是转发
由服务器端进行的页面跳转

原理图
在这里插入图片描述
转发的特点
地址栏不发生变化,显示的是上一个页面的地址
请求次数:只有1次请求
根目录:http://localhost:8080/项目地址/,包含了项目的访问地址
请求域中数据不会丢失
什么是重定向
概念
由浏览器端进行的页面跳转

原理图
在这里插入图片描述
重定向的特点
地址栏:显示新的地址
请求次数:2次
根目录:http://localhost:8080/ 没有项目的名字
请求域中的数据会丢失,因为是2次请求
疑问
1问:什么时候使用转发,什么时候使用重定向?

如果要保留请求域中的数据,使用转发,否则使用重定向。

以后访问数据库,增删改使用重定向,查询使用转发。

2问:转发或重定向后续的代码是否还会运行?

无论转发或重定向后续的代码都会执行
在这里插入图片描述

2 Springmvc的转发和重定向

什么都不写,默认的就是转发方式
ServletAPI
通过设置ServletAPI , 不需要视图解析器 .

1、通过HttpServletResponse进行输出

2、通过HttpServletResponse实现重定向

3、通过HttpServletResponse实现转发

@Controller
public class ResultGo {
    
    

   @RequestMapping("/result/t1")
   public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    
    
       rsp.getWriter().println("Hello,Spring BY servlet API");
  }

   @RequestMapping("/result/t2")
   public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    
    
       rsp.sendRedirect("/index.jsp");
  }

   @RequestMapping("/result/t3")
   public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
    
    
       //转发
       req.setAttribute("msg","/result/t3");
       req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
  }

}

SpringMVC
通过SpringMVC来实现转发和重定向 - 无需视图解析器;

测试前,需要将视图解析器注释掉

@Controller
public class ResultSpringMVC {
    
    
   @RequestMapping("/rsm/t1")
   public String test1(){
    
    
       //转发
       return "/index.jsp";
  }

   @RequestMapping("/rsm/t2")
   public String test2(){
    
    
       //转发二
       return "forward:/index.jsp";
  }

   @RequestMapping("/rsm/t3")
   public String test3(){
    
    
       //重定向
       return "redirect:/index.jsp";
  }
}

通过SpringMVC来实现转发和重定向 - 有视图解析器;

重定向 , 不需要视图解析器 , 本质就是重新请求一个新地方嘛 , 所以注意路径问题.

可以重定向到另外一个请求实现 .

@Controller
public class ResultSpringMVC2 {
    
    
   @RequestMapping("/rsm2/t1")
   public String test1(){
    
    
       //转发
       return "test";
  }

   @RequestMapping("/rsm2/t2")
   public String test2(){
    
    
       //重定向
       return "redirect:/index.jsp";
       //return "redirect:hello.do"; //hello.do为另一个请求/
  }

}

猜你喜欢

转载自blog.csdn.net/qq_44543774/article/details/121061176