Issue
I have a controller in Spring Boot that needs to recieve a parameter and an object by POST. The parameter is NOT an object or part of if.
Here is the Thymeleaf form without the parameter. It works fine in a stand-alone page, but the same code does not work when I use it in a page that shows an article:
<form th:action="@{/addcomment}" th:object="${comment}" method="post">
<input type="text" th:field="*{commenttext}" />
<button type="submit">send</button>
</form>
because when I add the
<input type="hidden" th:field="*{id}" th:with="id=1" value="${id}"/>
or
<input type="hidden" th:field="*{id}"/>
or
<input type="hidden" th:field="*{id}" value="1"/>
my Controller prints 0 in the console, when the value should be 1... (and even if I change it to value="true".... this comes from the Chrome console:
<input type="hidden" class="sr-only" value="0" id="id" name="id" />
no matter what I use
@RequestMapping(value = "/addcomment", method = RequestMethod.POST)
ModelAndView addStatus(ModelAndView modelAndView, @Valid Comment comment, @RequestParam("id") Long id, BindingResult result) {
Comment commentform = new Comment();
Announcement announcement = announcementService.readAnnouncement(id);
String sanatizedcommenttext = htmlPolicy.sanitize(comment.getCommenttext());
commentform.setCommenttext(sanatizedcommenttext);
commentform.setDate(new Date());
commentform.setAnnoucements(announcement);
modelAndView.setViewName("addcomment");
if (!result.hasErrors()) {
commentService.createComment(commentform);
modelAndView.getModel().put("comment2th", new Comment());
modelAndView.setViewName("redirect:/addcomment");
}
return modelAndView;
}
By the way, the parameter is in the url (but I would like to know how to send it to the controller independently of where it is located). thanks for your help!
Solution
You only have to add this changes
<input type="hidden" name="paramName" value="1"/>
In your Controller
@RequestMapping(value = "/addcomment", method = RequestMethod.POST)
ModelAndView addStatus(ModelAndView modelAndView, @Valid Comment comment, @RequestParam("paramName") Long id, BindingResult result) {
The problem was, that you were using the thymeleaf tags for input fields, then Spring thinks the attribute id its inside the object Comment, but it's not your case, so you have to use normal input tag.
Answered By - cralfaro
Answer Checked By - Mildred Charles (JavaFixing Admin)