2017-01-12 24 views
0

我有这样的形式: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)做这样的事情?有没有什么办法可以像循环这样做,或者什么是最好的解决方案?

回答

2

的输入设置的名称作为数组则params的名字:

<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

+0

它适用于RequestParam,但不适用于ModelAttribute。 qList中只有1个元素,而aList中只有0个元素。 – Helosze

+0

@Helosze @ @ ModelAttribute'对绑定参数没有任何作用。这个注解只是表示方法的参数应该添加到具有指定名称的模型中。你可以根本删除'@ ModelAttribute',但是值将被绑定。 –