SpringMVC跨重定向请求传递数据代码实现方法

作者:袖梨 2020-06-04

本篇文章小编给大家分享一下SpringMVC跨重定向请求传递数据代码实现方法,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

执行完post请求后,通常来讲一个最佳实践就是执行重定向。重定向将丢弃原始请求数据,原始请求中的模型数据和请求都会消亡。可以有效避免用户浏览器刷新或者后退等操作,直接间接地重复执行已经完成的post请求。

在控制方法中返回的视图名称中,在String前使用"redirect:"前缀,那么这个String就不是来查找视图的,而是浏览器进行重定向的路径,相当于重新发出请求。

重定向通常相当于从一个controller到另一个controller。

(1)使用URL模板以路径变量和查询参数的形式传递数据(一些简单的数据)

@GetMapping("/home/index")
  public String index(Model model){
    Meinv meinv = new Meinv("gaoxing",22);
    model.addAttribute("lastName",meinv.getLastName());
    model.addAttribute("age",meinv.getAge());
    return "redirect:/home/details/{lastName}";
  }

  @GetMapping("/home/details/{lastName}")
  public String details(@PathVariable String lastName, @RequestParam Integer age){
    System.out.println(lastName);
    System.out.println(age);
    return "home";
  }

(2)通过flash属性发送数据(对象等复杂数据)

@GetMapping("/home/index")
  public String index(RedirectAttributes model){
    Meinv meinv = new Meinv("gaoxing",22);
    model.addAttribute("lastName",meinv.getLastName());
    model.addFlashAttribute("meinv",meinv);
    return "redirect:/home/details/{lastName}";
  }

  @GetMapping("/home/details/{lastName}")
  public String details(@PathVariable String lastName, Model model){
    Meinv meinv = null;
    if(model.containsAttribute("meinv")){
      meinv = (Meinv) model.asMap().get("meinv");
    }
    System.out.println(meinv);
    return "home";
  }

相关文章

精彩推荐