Carrying data across redirect re

2020-03-05  本文已影响0人  cdz620

重定向携带数据方式

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";
}
上一篇 下一篇

猜你喜欢

热点阅读