Java Spring重定向属性未传输
我想将id参数从一个窗体(控制器)传递到另一个窗体(控制器)。 在这里,我将一个id添加到我的模型中,并将其传递Java Spring重定向属性未传输,java,spring-boot,spring-mvc,thymeleaf,Java,Spring Boot,Spring Mvc,Thymeleaf,我想将id参数从一个窗体(控制器)传递到另一个窗体(控制器)。 在这里,我将一个id添加到我的模型中,并将其传递 @Controller public class PersonController @RequestMapping(value = {"/addPerson"}, method = RequestMethod.POST) public String savePerson(Model model, //
@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
方法中,您正在添加一个attributes.addFlashAttribute()
而不是model.addAttribute()
方法,就像您在showAddKontoPage
方法中一样
这意味着,对于通过重定向从控制器传递到控制器的属性,您需要通过model.addAttribute()
方法添加该属性
您可以向控制器方法添加新属性以接受用户id属性:
@RequestMapping(value = {"/addKonto"}, method = RequestMethod.GET)
public String showAddKontoPage(Model model,
@RequestParam(required = false) String id)
用于通过标签向最终用户显示消息
旁注:
Spring有基础设施来支持它。当然,在您准备好以后使用该基础设施会更好。如果我添加这个model.addAttribute(“id”,newPerson.getId());对于savePerson,则showAddPersonPage不接受id。问题是在saveKonto中,模型只有kontoForm,没有用户id。size=3表示模型有kontoForm、validator和IDI如果表单中没有用户id,则需要通过控制器方法将值作为参数传递,或者,您需要将用户id添加到表单中。我建议通过方法属性传递用户id。我更新了答案以显示如何将参数属性传递给控制器方法。然后id为null
@RequestMapping(value = {"/addKonto"}, method = RequestMethod.POST)
public String saveKonto(Model model,
@ModelAttribute("kontoForm") KontoForm kontoForm,
@RequestParam(required = false) String id)