У меня есть два скрытых поля ввода для реализации системы Friend. Я передаю идентификаторы пользователя и друга в Model, а затем использую их на странице thymeleaf, чтобы передать их в форме PostMapping
и сохранить изменения. Однако PostMapping
не может видеть моего второго @RequestParam
.
И customer
, и friend
правильно передаются модели, так как я пытался вывести их на сайт с помощью 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";
Фрагмент кода Thymeleaf:
<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";
}
См. Обработка форм с помощью Thymeleaf для более подробного руководства по этому вопросу.