第二个隐藏输入未被读取



我有两个隐藏的输入字段来实现好友系统。我在Model中传递用户和朋友的id,然后在thymeleaf页面中使用它们将它们以表单传递给PostMapping并保存更改。然而,PostMapping看不到我的第二个@RequestParam

customerfriend都被正确地传递给模型,因为我试图在网站上使用th:text输出它们

代码片段:
添加两个用户到模型:

@GetMapping("/customer/{customerId}")
public String getCustomer(Model theModel, @PathVariable int customerId, @AuthenticationPrincipal MyUserDetails user) {
Customer currUser = customerService.findById(user.getCustomer().getId());
Customer foundCustomer = customerService.findById(customerId);
theModel.addAttribute("friend", foundCustomer);
theModel.addAttribute("customer", currUser);
return "customerdetails";


百里香代码片段:

<form action="#" th:action="@{/home/addFriend}" th:object="${friend}" method="post">
<input type="hidden" th:field="${friend.id}" th:attr="name='friendId'" />
<input type="hidden" th:field="${customer.id}" th:attr="name='customerId'" />
<input type="submit" value="Add Friend" class="btn btn-primary flex-grow-1" />
</form>


PostMapping(出现问题的地方):

@PostMapping("/addFriend")
public String getPost(@RequestParam("friendId") int friendId, @RequestParam("customerId") int customerId) {
Customer friendCustomer = customerService.findById(friendId);
Customer currCustomer = customerService.findById(customerId);

System.out.println(currCustomer.getFirstName());
System.out.println(friendCustomer.getFirstName());

return "redirect:/home";
}
错误码:
[org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'friendId' for method parameter type int is not present]

使用自定义表单对象会容易得多。

例如,创建这个类:

public class AssignFriendFormData {
private String friendId;
private String customerId;
// getter and setters here
}

在你的@GetMappping:

@GetMapping("/customer/{customerId}")
public String getCustomer(Model theModel, @PathVariable int customerId, @AuthenticationPrincipal MyUserDetails user) {
Customer currUser = customerService.findById(user.getCustomer().getId());
Customer foundCustomer = customerService.findById(customerId);
AssignFriendFormData formData = new AssignFriendFormData();
formData.setFriendId(foundCustomer.getId());
formData.setCustomerId(currUser.getId());
theModel.addAttribute("formData", formData);

return "customerdetails";

将表单更改为:

<form action="#" th:action="@{/home/addFriend}" th:object="${formData}" method="post">
<input type="hidden" th:field="*{friendId}" />
<input type="hidden" th:field="*{customerId}" />
<input type="submit" value="Add Friend" class="btn btn-primary flex-grow-1" />
</form>

最后,更新@PostMapping以使用表单数据对象:

@PostMapping("/addFriend")
public String getPost(@Valid @ModelAttribute("formData") AssignFriendFormData formData) {
Customer friendCustomer = customerService.findById(formData.getFriendId());
Customer currCustomer = customerService.findById(formData.getCustomerId());

System.out.println(currCustomer.getFirstName());
System.out.println(friendCustomer.getFirstName());

return "redirect:/home";
}

参见Form handling with Thymeleaf获得更深入的教程。

最新更新