重定向携带数据方式
- 简单的数据格式通过 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";
}
网友评论