英文:
Spring mvc from doesn't call controller
问题
我是新手使用Spring框架,我只是在创建自己的项目以便理解。这个流程是登录 -> 客户列表 -> 选择一个客户 -> 宠物列表。
在第一页上有一个带有表单的按钮,用于添加客户,它能正常工作。然而,类似的代码在第二个页面上用于添加宠物的按钮却不能正常工作。当我尝试保存新的宠物时,它返回HTTP 400 - 错误的请求,控制台中没有任何信息。
pet-form.jsp:
<form:form action="${pageContext.request.contextPath}/pet/savePet"
modelAttribute="pet" method="POST">
<!-- 需要将此数据与客户ID关联起来 -->
<form:hidden path="owner.id" />
......
<td><input type="submit" value="保存" class="save" /></td>
</tr>
</tbody>
</table>
PetController.java:
@Controller
@RequestMapping("/pet")
public class PetController {
......
@PostMapping("/savePet")
public String savePet(@ModelAttribute("pet") Pet thePet) {
System.out.println("新的宠物 " + thePet.toString());
thePet.setOwner(customerService.getCustomer(thePet.getOwner().getId()));
System.out.println("控制器 " + thePet);
// 使用我们的服务保存客户
petService.savePet(thePet);
return "redirect:/pet/showListPets";
}
}
有什么想法是出了什么问题吗?
提前感谢。
英文:
I'm new using spring framework and I'm just creating my own project in order to catch the idea. The flow of this is loging -> customer list -> select one cusstomer -> Pet list.
I have a button on first page with a form in order to add a customer and it is working properly. However, similar code to a second button in pet page to add a pet is not working. When I try to save the new pet, it is returning HTTP 400 – Bad Request and nothing in the console
pet-form.jsp :
<form:form action="${pageContext.request.contextPath}/pet/savePet"
modelAttribute="pet" method="POST">
<!-- need to associate this data with customer id -->
<form:hidden path="owner.id" />
......
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
PetController.java
@Controller
@RequestMapping("/pet")
public class PetController {
.....
@PostMapping("/savePet")
public String savePet(@ModelAttribute("pet") Pet thePet) {
System.out.println("New Pet " + thePet.toString());
thePet.setOwner(customerService.getCustomer(thePet.getOwner().getId()));
System.out.println("Controller" + thePet);
// save the customer using our service
petService.savePet(thePet);
return "redirect:/pet/showListPets";
}
Any ideas what is happening?
Thanks in advance
答案1
得分: 0
我解决了我的问题,但是我不明白为什么,所以,如果有人能够友好地解释一下给我..那会更好:)
问题通过将BindingResult参数添加到控制器方法中得以解决:
@PostMapping("/savePets")
public String savePets(@ModelAttribute("pet") Pet thePet, BindingResult result) {
英文:
I resolved my question, however I dont understand why, so , if someone is so kind to explain me.. better
The problem was solved adding BindingResult paramenter to the controller method :
@PostMapping("/savePets")
public String savePets(@ModelAttribute("pet") Pet thePet, BindingResult result) {
Thanks
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论