2017-01-12 32 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',但是值將被綁定。 –