java - Spring redirectAttributes 未传输
问题描述
我想将 id 参数从一种形式(控制器)传递到另一种形式。在这里,我向我的模型添加了一个 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";
}
当我尝试进一步传递我的模型时,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
方法中,您添加的是 aattributes.addFlashAttribute()
而不是model.addAttribute()
像您在showAddKontoPage
方法中一样。
这意味着,对于要通过重定向从控制器传递到控制器的属性,您需要通过该model.addAttribute()
方法添加该属性。
您可以向控制器方法添加新属性以接受用户 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 Messages用于通过标签向最终用户显示消息。
附带说明:
Spring 具有验证表单的基础设施。当然,当您准备好使用该基础架构时,将来使用该基础架构会更好。
推荐阅读
- java - 分析 Java 代码会更改执行时间
- angular - 从单个数字中删除前导零
- sql - 从具有附加连接的另一个查询结果中选择
- reactjs - `component` 属性如何与 Tab 组件一起使用?
- django-cms - Django CMS 链接 - AttributeError 'Page' 对象没有属性 'site'
- django - Django foreignKey 不使用模型的主键来匹配外部对象的主键?
- javascript - 如何在javascript中访问获取数据?
- java - Mybatis queryFromDatabase 函数中的 NullPointerException
- floating-point - Chebychev 点和浮点精度
- java - 爪哇 | 如何让其中一个线程休眠而其他线程仍在运行?