How to pass th:object values from html to controller

Java_User picture Java_User · Aug 17, 2015 · Viewed 37.5k times · Source

How to pass thymeleaf(th:object) values to controller.

HTML:

<form id="searchPersonForm" action="#" th:object="${person}" method="post" >  
</form>

SearchPersonController:

@RequestMapping(value = "/modify/{pid}", method = RequestMethod.GET)
    public String modifyPersonData(Principal principal, @ModelAttribute("person") Person person, UserRoles userRoles, Model model, @PathVariable("pid") Long pid ) {
         //modify data
    }

I am trying to pass like @ModelAttribute("person") Person person but this is not retrieving form values from previous page.

Can anyone help on this.

Thanks.

Answer

Evil Toad picture Evil Toad · Aug 17, 2015

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.