Thymeleaf - 不同数量的参数

时间:2017-01-12 13:55:26

标签: java spring thymeleaf

我有这样的表格:

<form th:action="@{'/articles/' + ${article.id} + '/processTest'}" method="post">
    <table>
        <tr th:each="entry,iter: ${wordsWithTranslation}">
            <td><input type="text" th:value="${entry.key.value}" th:name="'q' + ${iter.index}" readonly="readonly"/>
            </td>
            <td> -----</td>
            <td><input type="text" th:name="'a' + ${iter.index}"/></td>
        </tr>
    </table>
    <br/>
    <input type="submit" value="Sprawdź"/>
</form>

wordsWithTranslation是一个HashMap,它可以包含不同数量的元素。

控制器:

public String processTest(Model model, @PathVariable Long id, 
@ModelAttribute(value = "q0") String q0, 
@ModelAttribute(value = "a0") String a0, 
@ModelAttribute(value = "q1") String q1,
@ModelAttribute(value = "a1") String a1)

如何解决方法参数不能做那样的事情(每个q和一个值的ModelAttribute)?有什么办法可以在这里做一些循环或者什么是最好的解决方案?

1 个答案:

答案 0 :(得分:2)

将输入名称设置为数组参数的名称:

<form th:action="@{'/articles/' + ${article.id} + '/processTest'}" method="post">
    <table>
        <tr th:each="entry : ${wordsWithTranslation}">
            <td>
                <input type="text" th:value="${entry.key.value}" name="q[]" readonly="readonly"/>
            </td>
            <td> -----</td>
            <td><input type="text" name="a[]"/></td>
        </tr>
    </table>
    <input type="submit" value="Sprawdź"/>
</form>

现在在控制器中,您可以将此字段接受为List<>array

@RequestMapping(value='/articles/{id}/processTest')
public String someMethod(Model model, @PathVariable Long id, 
                         @RequestParam(value = "q[]") List<String> qList,
                         @RequestParam(value = "a[]") List<String> aList){
    ...
}

列表q中的每个项目都对应于列表a的某些项目。