【发布时间】:2017-09-29 11:44:24
【问题描述】:
我正在做一个简单的项目,但不知何故我无法“捕捉”对/collaborators/add 的 POST 方法调用
我找不到错误,也许很明显(我是新手)...有人可以快速看一下吗?
html 表单:
<form action="/collaborators/add" method="post">
<h2>Manage Collaborators</h2>
<ul class="checkbox-list">
<li th:each="c : ${collaborators}">
<span class="primary" th:text="${c.name}">Michael Pemulius</span>
<div class="custom-select">
<span class="dropdown-arrow"></span>
<select>
<option value="#" selected="selected">Designer</option>
</select>
</div>
</li>
</ul>
<div class="actions add-new-collaborator" th:object="${collaborator}">
<input type="text" placeholder="Name..." th:field="*{name}"/>
<div class="custom-select">
<span class="dropdown-arrow"></span>
<select th:field="*{role}">
<option value="#" disabled="disabled" selected="selected">Role...</option>
<option th:each="r : ${roles}" th:value="${r}" th:text="${r.name}">Developer</option>
</select>
</div>
<button class="button" type="submit">Add</button>
</div>
</form>
控制器:
@RequestMapping(value = "/collaborators/add", method = RequestMethod.POST)
public String addCollaborator(Model model, @Valid Collaborator collaborator, RedirectAttributes redirectAttributes, BindingResult bindingResult) {
System.out.println("Executed");
if (bindingResult.hasErrors()) {
System.out.println("but with errors");
System.out.println(bindingResult.getFieldError());
redirectAttributes.addFlashAttribute("flashMessage", new FlashMessage("The collaborator was not created", FlashMessage.Status.FAILURE));
redirectAttributes.addFlashAttribute("collaborator", collaborator);
return "redirect:/collaborators";
}
collaboratorService.save(collaborator);
redirectAttributes.addFlashAttribute("flashMessage", new FlashMessage("The collaborator was created", FlashMessage.Status.SUCCESS));
return "redirect:/collaborators";
}
控制台中没有错误信息,只有 400。
我认为问题出在百里香!这里:
<div class="custom-select">
<span class="dropdown-arrow"></span>
<!--<select th:field="*{role}">-->
<select>
<option value="#" disabled="disabled" selected="selected">Role...</option>
<!--<option th:each="r : ${roles}" th:value="${r}" th:text="${r.name}">Developer</option>-->
<option th:each="r : ${roles}" th:value="${r}" th:text="${r.name}">Developer</option>
</select>
</div>
我很确定是对象绑定出错。
【问题讨论】:
-
您的表单数据保存在
Model对象中,因此您应该将模型传递给您的方法参数并从那里读取它。或者使用@ModelParameter注释这可能是问题所在。我希望您不要像您在帖子中显示的那样尝试使用反斜杠 (\) 来调用它。错误消息也很好。见this guide -
试试这个,看看它是否有效:删除表单标签中的第一个
/,即action="collaborators/add"而不是action="/collaborators/add" -
你说得对,我错过了模型(我编辑了问题)。我现在在那里,但它还没有收到请求......
-
@JackFlamp,改变了,不...
-
尝试运行您的浏览器开发工具并检查网络选项卡。提交表单时尝试 POST 的 URL 是什么?
标签: spring forms spring-mvc controller thymeleaf