【发布时间】:2017-04-28 11:19:06
【问题描述】:
编辑: 如果有人在遵循以下指南时遇到问题,我建议使用更简单的方法,例如:https://www.youtube.com/watch?v=yaxUV3Ib4vM
我仍在学习本教程:spring-mvc-radiobutton-and-radiobuttons-example,到目前为止我已经创建了这个控制器:
@RequestMapping(value = "add", method = RequestMethod.GET)
public String add(Model model) {
MyObject object = new MyObject();
object.setParameter("fake parameter");
model.addAttribute("add", object);
initModelList(model);
return "add";
}
@RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@ModelAttribute("add") @Validated MyObject object, BindingResult result, Model model) {
model.addAttribute("add", object);
String returnVal = "redirect:/add/object";
if(result.hasErrors()) {
initModelList(model);
returnVal = "add";
} else {
model.addAttribute("add", object);
}
return returnVal;
}
@RequestMapping(value = "/add/object", method = RequestMethod.POST)
public String addObject(
@ModelAttribute MyObject object,
ModelMap model) throws DatatypeConfigurationException {
try{
...marshalling results in xml output
...inserting it in database
...showing the result
return "objectResult";
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
这个解决方案当然行不通,因为重定向是 GET 类型的。 我尝试将最后两种方法融合在一起,如下所示:
@RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@ModelAttribute("add") @Validated MyObject object, BindingResult result, Model model)
throws DatatypeConfigurationException {
model.addAttribute("add", object);
String returnVal = "objectResult";
if(result.hasErrors()) {
initModelList(model);
returnVal = "add";
} else {
model.addAttribute("add", object);
}
try{
...mashalling etcetera
return returnVal;
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
但是这样验证不起作用。我不知道如何解决这个问题,我想使用 spring 验证器,但如果我不能使用它,我将退回项目,这是一个耻辱。
【问题讨论】:
-
什么不起作用?重定向工作得很好,它甚至是post-redirect-get 的模式。所以不确定什么不起作用,但我想这与你的理解有关(看看你的代码,它首先已经充满了黑客攻击)。
-
重定向不起作用,因为我收到消息“不支持请求方法'GET'”,即使在我的控制器中我将其映射为 RequestMethod.POST。由于我是新手,我可能不了解指南和其他一些内容。
-
嗯,我很清楚的消息是不是...重定向是,正如你所说的 GET,但你没有方法。所以是的,那么您将收到该消息,因为没有任何东西可以处理 GET。
-
我想避免在这种情况下使用 GET,并知道是否有办法重定向到我的页面维护 post 方法。在没有验证器的情况下,我使用了上面的 post 方法,它工作正常。
-
第二种方法验证的错误是什么?没有理由需要两种方法来验证然后进行逻辑 - 我可以从代码中看到,第二种方法检查错误然后继续处理,这只是需要返回那里的错误情况的情况吗?
标签: java spring spring-mvc spring-boot spring-validator