我有一个页面来添加用户" / user / userAdd"。在GET中,我填写了一个国家列表。在POST中,我从formsubmit验证User对象。如果有错误,我将返回错误消息的同一页面。我的问题是我只是做一个简单的回复" / user / userAdd&#34 ;;未填充国家/地区列表。如果我做了返回"重定向:/ user / userAdd&#34 ;;我正在丢失以前的用户输入。我该怎么办呢?
@RequestMapping(value = "/user/userAdd", method = RequestMethod.GET)
public void getUserAdd(Model aaModel) {
aaModel.addAttribute("user", new User());
List<Country> llistCountry = this.caService.findCountryAll();
aaModel.addAttribute("countrys", llistCountry);
}
@RequestMapping(value = "/user/userAdd", method = RequestMethod.POST)
public String postUserAdd(@ModelAttribute("user") @Valid User user,
BindingResult aaResult, SessionStatus aaStatus) {
if (aaResult.hasErrors()) {
return "/user/userAdd";
} else {
user = this.caService.saveUser(user);
aaStatus.setComplete();
return "redirect:/login";
}
}
答案 0 :(得分:2)
我的春季项目也遇到了类似的问题。我建议将POST方法更改为以下
@RequestMapping(value = "/user/userAdd", method = RequestMethod.POST)
public String postUserAdd(@ModelAttribute("user") @Valid User user,
BindingResult aaResult, Model aaModel, SessionStatus aaStatus) {
if (aaResult.hasErrors()) {
List<Country> llistCountry = this.caService.findCountryAll();
aaModel.addAttribute("countrys", llistCountry);
return "/user/userAdd";
} else {
user = this.caService.saveUser(user);
aaStatus.setComplete();
return "redirect:/login";
}
}
此处,列表再次添加到模型中,并且还将保留UI中先前选择的值(如果有)。
希望这有帮助