简体   繁体   中英

How to pass data to from view to controller in Spring-MVC?

I have a list of objects as JSON which is inside a workLists. I created a table by iterating using each on workLists and create a table in thymeleaf?

Now how can I pass work that is a single object back to the controller, what I tried is using th:object I thought it would work but on the controller end null values are coming.

Thymeleaf section

<tr th:each="work , status : ${workLists}">
    <td scope="row" th:text="${status.count}"></td>
    <td>
    <form th:action="@{/edit/work}" th:object="${work}" method="post">
        <button type="submit" class="dropdown-item">Edit</button>
    </form>
    </td>
</tr>

Controller Section

@PostMapping("/edit/work")
    public String editWork(@ModelAttribute("work") GetWorkkDto getWorkDto){
        logger.debug(" Inside of edit work method");
        return "listOfwork";
    }

You need to give the contoller 2 attribues which are the workLists and a work. It will be something like:

@GetMapping("/edit/work")
public String editWork(Model model){
    model.addAttribute("workLists", workLists);
    model.addAttribute("workDTO", new Work());
    return "listOfwork";
}

Then in your HTML page through hidden fields you give the values of the work selected:

<table>
    <tr th:each="work, stat : ${workLists}">
            <td>
                <form action="#" th:action="@{/edit/work}" th:object="${workDTO}" method="post">
                    <input type="hidden"  th:attr="name='id'"  th:value="${work.id}" />
                    <input type="hidden"  th:attr="name='name'"  th:value="${work.name}" />
                    <input type="hidden"  th:attr="name='description'"  th:value="${work.description}" />
                    <p th:text="'Id : '+${work.id}"></p>
                    <p th:text="'Name : '+${work.name}"></p>
                    <p th:text="'Description : '+${work.description}"></p>
                    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
                
                </form>
            </td>
    </tr>
</table>

You can see in the proposed code that I give the value of work.id to the workDTO.id through the name attribute (don't ask me why it is like this)

Finaly you retrieve the object in your controller (as you do already) with something like this:

@PostMapping("/edit/work")
public String editWork(@ModelAttribute Work workDTO, Model model){
    System.out.println(workDTO.toString());
    model.addAttribute("workLists", workLists);
    model.addAttribute("workDTO", new Work());
    return "listOfwork";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM