2013-10-09 39 views
4

我有一個類是這樣的:綁定映射(鍵和值),以彈簧形式在JSP

public class MyClass { 
    private Map<String, String> properties = new HashMap<String, String>(); 
} 

我需要一個形式,其中用戶可以在屬性映射添加關鍵值對。我在此找到所有答案SO只是展示瞭如何使用已知鍵使用輸入值:

<form:input path="properties['keyName']" /> 

我怎樣才能讓鍵編輯也?我喜歡...

<form:input path="properties.key" /><form:input path="properties.value" /> 
+0

有沒有人對此有過評論?我也陷入了類似的情況。 – Heisenberg

回答

0

我得到了這個工作,不得不再次找到這個頁面來提供我的答案。

我正在動態地向我的<form>添加一個密鑰和值映射,我的解決方案有一個關鍵輸入和一個單獨的輸入值。然後我在密鑰上註冊了一個更改監聽器,以更新值輸入上的name

對我來說,最難的部分是JQuery無法訪問動態添加的鍵/值元素的ID。這意味着如果地圖已經被填充,我可以毫無問題地使用JQuery,但是如果它是一個新條目,我遇到了問題,並且對值輸入的ID進行搜索並不成功。

爲了解決這個問題,我不得不基本旅行DOM來獲取值輸入。這是我的代碼JSP代碼。

<c:forEach var="points" items="${configuration.pointsValueMap}" varStatus="index"> 
    <div class="col-xs-3 "> 
    <label for="pointMap[${index.index}]">Type:</label> 
    <input type="text" id="pointMap[${index.index}]" class="pointMap" value="${points.key}"> : 
    </div> 
    <div class="col-xs-3 "> 
    <label for="pointMap[${index.index}]-value">Value:</label> 
    <input type="text" id="pointMap[${index.index}]-value" name="pointsValueMap[${points.key}]" value="${points.value}"> 
    </div> 
</c:forEach> 

這裏是我的JS更新名稱路徑的值。

/** 
* Register a listener on the form to detect changing the map's key 
*/ 
$('form').on('change', 'input.pointMap', function(){ 
    var content = $(this).val(); 
    var id = $(this).attr('id'); 
    // have to travel the DOM for added elements to be accessed. 
    // JQuery does not have visibility to the IDs of added elements 
    $(this).parent().next().children('input').attr('name', 'pointsValueMap['+content+']'); 
    // if you are not dynamically adding key/values then 
    // all fields are accessible by JQuery and you can update by: 
    $('#'+id+'-value').attr('name', 'pointsValueMap['+content+']'); 
});