[英]Spring redirectAttributes not transferred
我想将 id 参数从一种形式(控制器)传递到另一种形式。 在这里,我在我的 model 中添加了一个 id 并将其传递。
@Controller
public class PersonController
@RequestMapping(value = {"/addPerson"}, method = RequestMethod.POST)
public String savePerson(Model model, //
@ModelAttribute("personForm") PersonForm personForm, RedirectAttributes attributes) {//, @ModelAttribute("person") Person newPerson) {
String firstName = personForm.getFirstName();
String lastName = personForm.getLastName();
double money = personForm.getMoney();
if (firstName != null && firstName.length() > 0
&& lastName != null && lastName.length() > 0) {
Person newPerson = new Person(firstName, lastName, money);
personService.save(newPerson);
attributes.addFlashAttribute("id", newPerson.getId());//
return "redirect:/addKonto";
}
model.addAttribute("errorMessage", errorMessage);
return "addPerson";
}
我将数据传递给另一个表单,这里的 id 被正确传递。 大小 = 3
@RequestMapping(value = {"/addKonto"}, method = RequestMethod.GET)
public String showAddKontoPage(Model model, @ModelAttribute("id") int id) {
KontoForm kontoForm = new KontoForm();
model.addAttribute("kontoForm", kontoForm);
model.addAttribute("id", id);
return "addKonto";
}
当我尝试进一步传递我的 model 时,id 参数会丢失。 大小 = 2
@RequestMapping(value = {"/addKonto"}, method = RequestMethod.POST)
public String saveKonto(Model model,
@ModelAttribute("kontoForm") KontoForm kontoForm) {
String kontoName = kontoForm.getKontoName();
double moneyInKonto = kontoForm.getMoneyInKonto();
model.getAttribute("id"); // hier is null
if (kontoName != null && kontoName.length() > 0) {
Konto newKonto = new Konto(kontoName, moneyInKonto);
kontoService.save(newKonto);
return "redirect:/personList";
}
如何获取id参数?
在您的savePerson
方法中,您添加了attributes.addFlashAttribute()
而不是model.addAttribute()
就像您在showAddKontoPage
方法中一样。
意思是,对于要通过重定向从 controller 传递到 controller 的属性,您需要通过model.addAttribute()
方法添加该属性。
您可以向 Controller 方法添加新属性以接受用户 ID 属性:
@RequestMapping(value = {"/addKonto"}, method = RequestMethod.GET)
public String showAddKontoPage(Model model,
@RequestParam(required = false) String id)
@RequestMapping(value = {"/addKonto"}, method = RequestMethod.POST)
public String saveKonto(Model model,
@ModelAttribute("kontoForm") KontoForm kontoForm,
@RequestParam(required = false) String id)
Flash 消息用于通过标签向最终用户显示消息。
附带说明:
Spring 具有验证您的 Forms的基础设施。 当然,当您准备好使用该基础架构时,将来使用该基础架构会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.