美文网首页
Carrying data across redirect re

Carrying data across redirect re

作者: cdz620 | 来源:发表于2020-03-05 10:21 被阅读0次

重定向携带数据方式

  • 简单的数据格式通过 path variables 或者query parameters
  • 通过Model flash attributes

path variables or query parameters

@RequestMapping(value="/register", method=POST)
public String processRegistration(Spitter spitter, Model model) {
  spitterRepository.save(spitter);
  model.addAttribute("username", spitter.getUsername());
  model.addAttribute("spitterId", spitter.getId());
  return "redirect:/spitter/{username}";
}

重定向后的url: /spitter/habuma?spitterId=42

flash attributes

原理:将object保存到session中,由RedirectAttributes管理声明周期

重定向前, 写入object

@RequestMapping(value="/register", method=POST)
public String processRegistration(Spitter spitter, RedirectAttributes model) {
  spitterRepository.save(spitter);
  model.addAttribute("username", spitter.getUsername());
  model.addFlashAttribute("spitter", spitter);
  return "redirect:/spitter/{username}";
}

重定向后,读取object

Model 把object传递到view里

@RequestMapping(value = "/{username}", method = GET) 
public String showSpitterProfile(@PathVariable String username, Model model) {
    if (!model.containsAttribute("spitter")) {
        model.addAttribute(spitterRepository.findByUsername(username));
    }
    return "profile";
}

相关文章

网友评论

      本文标题:Carrying data across redirect re

      本文链接:https://www.haomeiwen.com/subject/dkdjchtx.html