Preferably use th:action
as a form attribute instead of action
, and specify the binding like the following:
<form th:action="@{/the-action-url}" method="post"
th:object="${myEntity}">
<div class="modal-body">
<div class="form-group">
<label for="name">Name</label> <input type="text"
class="form-control" id="name" th:field="*{name}"> </input>
</div>
<div class="form-group">
<label for="description">Description</label> <input type="text"
class="form-control" id="description"
th:field="*{description}"> </input>
</div>
</div>
</form>
I back this form with a Spring controller that initializes the model attribute (myEntity
object in the form). This is the relevant part of the controller class:
@ModelAttribute(value = "myEntity")
public Entity newEntity()
{
return new Entity();
}
The @ModelAttribute
annotation ensures that the model object is initialized by Spring for every request.
Set a model named "command" during the first get request to your controller:
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView getRanks(Model model, HttpServletRequest request)
{
String view = "the-view-name";
return new ModelAndView(view, "command", model);
}
And, to access the model as it results after the form submission, implement the relative method:
@RequestMapping(value = "/the-action-url", method = RequestMethod.POST)
public View action(Model model, @ModelAttribute("myEntity") Entity myEntity)
{
// save the entity or do whatever you need
return new RedirectView("/user/ranks");
}
Here, the parameter annotated with @ModelAttribute
is automatically bound to the submitted object.
th:action="@{/the-action-url}"
. 2.Earlier I was using ` RequestMethod.POST` formodifyPersonData
and I gotPerson
form values from view by just usingPerson person
without@ModelAttribute("person")
. But when I changed to ` RequestMethod.GET, I am not able to retrieve
Person ` values and I tried with@ModelAttribute("person") Person person
and this is not working too. – Corrianne