有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java提供了不同数量的参数

我有这个表格:

<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和a值的ModelAttribute)?有没有什么方法可以在这里进行类似的循环,或者什么是最好的解决方案


共 (1) 个答案

  1. # 1 楼答案

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

    <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中的某一项