Reputation: 49
How can I send an object from a View to a Controller?
I'm first using a Controller 1 to display this object on a View 1 using Thymeleaf, the object is ${object}
. Then what I want to do is to click a button and send this object back to a Controller 2 so that I can display that same object from View 1 to View 2. How do you do that, can you give me an example please?
Right now I can do that using the ID of the object in the URL and then requesting the parameter in Controller 2, then getting the object based on the ID. But I don't want to see the object ID in the URL, what is another method?
Upvotes: 1
Views: 755
Reputation: 26848
If you don't want to use an id in the URL, then you can create a form with a hidden field and submit that to your controller.
<form th:object="${formData}" method="post">
<input type="hidden" th:field="*{id}">
<button type="submit">
</form>
With the controller like this:
@Controller
public class MyController {
@GetMapping
public String showPage(Model model) {
model.addAttribute("formData", new MyFormData("someId"));
return "myTemplate";
}
@PostMapping
public String handleId(@ModelAttribute("formData") MyFormData formData) {
String id = formData.getId();
// do something with id here
}
}
But it seems you make it a bit hard with this requirement. Any particular reason you don't want to show the id in the URL?
Upvotes: 1