2014-06-23 103 views
1
到控制器

我有一個簡單的HTML頁面,在這裏我展示一些radio buttons如何從單選按鈕發送數據與Thymeleaf

<form action="#" th:action="@{/processForm}" th:object="${priorities}" 
    method="post"> 
    <fieldset> 
    <table style="width: 500px"> 
     <tr th:each="item : ${chosen}"> 
     <td> 
      <div> 
      <div> 
       <label th:text="${item}">example</label> 
       <input type="radio" th:name="${'priorities[' + item + ']'}" value="a" />A 
       <input type="radio" th:name="${'priorities[' + item + ']'}" value="b" />B 
       <input type="radio" th:name="${'priorities[' + item + ']'}" value="c" />C 
      </div> 
      </div> 
     </td> 
     </tr> 
     <tr> 
     <td></td> 
     <td></td> 
     </tr> 
     <tr> 
     <td> 
      <button type="submit" 
      class="btn btn-xs btn-primary margin10-right paddingNew" 
      name="save">Calculate!</button> 
     </td> 
     <td></td> 
     </tr> 
    </table> 
    </fieldset> 
</form> 

在這裏,你得到了什麼,我可以看到:

radios

我想將這些數據發送到我的控制器,所以我創建了一個:

@RequestMapping(value = "/processForm", method = RequestMethod.POST) 
public String save(@ModelAttribute(value = "foo") ClusterParams foo, 
@ModelAttribute(value = "priorities") HashMap<String, String> priorities, 
final ModelMap m) throws ClassNotFoundException, IOException, 
InterruptedException { 

    for (String s : priorities.keySet()) { 
     System.out.println(s); 
    } 
} 

在這裏,你可以看到我的類權重(刪除):

public class Weights { 

    Map<String, String> priorities = new HashMap<String, String>(); 

    public Map<String, String> getPriorities() { 
     return priorities; 
    } 

    public void setPriorities(Map<String, String> priorities) { 
     this.priorities = priorities; 
    } 

} 

,但我不知道如何與thymeleaf設置的值。

我想獲得一個映射:

camera -> B 
video -> C 

你能幫我做到這一點?當然,這是我的想法,創建一個HashMap,如果有任何其他的解決方案,我會改變它。

預先感謝您

回答

3

6.4.1 Setting and getting basic and nested properties,你應該在生成的HTML <input>的名字,如priorities[camera],使其工作。

嘗試以下操作:

<input type="radio" th:name="${'priorities[' + item + ']'}" value="a" /> 
+0

你好,謝謝你。我改變了我的'html'頁面和''controller'(我編輯了我的文章)。我看不到任何輸出..我改變了名字,一切看起來都很好,但它不起作用。先謝謝你。 – ruhungry

+1

你的控制器應該像以前一樣使用'Weights'。 – axtavt