【发布时间】:2013-08-10 19:59:30
【问题描述】:
我的 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 方法中相同的行为?
【问题讨论】:
-
看看stackoverflow.com/questions/18039064/…,您可以使用 FlashAttributes 将数据传递给重定向视图。
-
这个解决方案比重定向更好,因为表单字段的值被保存了。但在这种情况下,我为此表单丢失了
BindingResult,因此在表单提交后我仍然无法向用户显示验证错误。 -
您可以将 BindingResult 与其他数据一起传递,请参阅stackoverflow.com/questions/2543797/…
-
谢谢,现在可以了。以前我尝试使用
FlashAttributes传递BindingResult对象,但我无法通过@ModelAttribute在我的buyGet方法中获取它,因为BindingResult不包含默认构造函数并且无法实例化。所以我通过会话传递了这个对象,看起来有点棘手。 -
Hippoom,您可以将您的 cmets 格式化为答案,我会接受它作为正确答案。
标签: validation spring-mvc