我的SpringMVC控制器中有下一个工作代码:
@RequestMapping(value = "/register", method = RequestMethod.GET)
public void registerForm(Model model) {
model.addAttribute("registerInfo", new UserRegistrationForm());
}
@RequestMapping(value = "/reg", method = RequestMethod.POST)
public String create(
@Valid @ModelAttribute("registerInfo") UserRegistrationForm userRegistrationForm,
BindingResult result) {
if (result.hasErrors()) {
return "register";
}
userService.addUser(userRegistrationForm);
return "redirect:/";
}
总之create
方法尝试验证UserRegistrationForm
。如果表单有错误,它会让用户在同一页面上填写表单字段,其中将显示错误消息。
现在我需要将相同的行为应用到另一个页面,但这里我有一个问题:
@RequestMapping(value = "/buy/{buyId}", method = RequestMethod.GET)
public String buyGet(HttpServletRequest request, Model model, @PathVariable long buyId) {
model.addAttribute("buyForm", new BuyForm());
return "/buy";
}
@RequestMapping(value = "/buy/{buyId}", method = RequestMethod.POST)
public String buyPost(@PathVariable long buyId,
@Valid @ModelAttribute("buyForm") BuyForm buyForm,
BindingResult result) {
if (result.hasErrors()) {
return "/buy/" + buyId;
}
buyForm.setId(buyId);
buyService.buy(buyForm);
return "redirect:/show/" + buyId;
}
我遇到了动态网址的问题。现在,如果表单有错误,我应该指定相同的页面模板留在当前页面上,但我也应该buyId
作为路径变量传递。这两个要求哪里有冲突。如果我保留此代码,则会收到错误消息(我使用Thymeleaf作为模板处理器):
Error resolving template "/buy/3", template might not exist or might not be accessible by any of the configured Template Resolvers
我可以写类似的东西return "redirect:/buy/" + buyId
,但在这种情况下,我会丢失表单对象的所有数据和错误。
我应该怎么做才能在方法中实现与buyPost
方法中相同的行为create
?