[英]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.我有一个对象列表作为 JSON,它位于 workLists 中。 I created a table by iterating using each on workLists and create a table in thymeleaf?
我通过在 workLists 上迭代使用 each 来创建一个表并在 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.现在如何将单个对象的
work
传递回控制器,我尝试使用th:object
我认为它会起作用,但在控制器端空值即将到来。
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.您需要为控制器提供 2 个属性,即工作列表和工作。 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:然后在您的 HTML 页面中通过隐藏字段提供所选作品的值:
<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)在建议的代码中可以看到我通过name属性给workDTO.id赋予了work.id的值(不要问我为什么会这样)
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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.