我正在做一个简单的项目,不知怎的,我无法抓住" POST方法调用/collaborators/add
我无法找到错误,也许很明显(我是新手)......有人可以快点看看吗?
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>
我很确定对象绑定是错误的。
答案 0 :(得分:2)
只是为了澄清答案:
我在做:
<form action="/collaborators/add" method="post">
...
<div class="actions add-new-collaborator" th:object="${collaborator}">
...
</div>
</form>
所以我在div中绑定了我的对象,这是错误的。
对象必须绑定在表单中,所以不要这样做,请执行:
<form th:action="@{/collaborators/add}" method="post" th:object="${collaborator}">
...
<div class="actions add-new-collaborator" th:object="${collaborator}">
...
</div>
</form>
它已经解决了!
答案 1 :(得分:1)
您需要稍微修改一下html。
<form th:action="@{/collaborators/add}" method="post" th:object="${collaborator}">
//here you can bind all attributes inside collaborator
这将是你需要做的所有改变