Abb*_*bby 5 java forms binding spring jsp
我有一个这样的课:
public class MyClass {
private Map<String, String> properties = new HashMap<String, String>();
}
Run Code Online (Sandbox Code Playgroud)
我需要一个表单,用户可以在属性映射中添加键值对.我在这里找到的所有SO答案都只显示如何使用已知密钥输入值:
<form:input path="properties['keyName']" />
Run Code Online (Sandbox Code Playgroud)
我怎样才能使密钥可编辑?我喜欢......
<form:input path="properties.key" /><form:input path="properties.value" />
Run Code Online (Sandbox Code Playgroud)
我得到了这个工作,不得不再次找到这个页面来提供我的答案。
我动态地向我的解决方案添加一个键和值映射,<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>
Run Code Online (Sandbox Code Playgroud)
这是我的 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+']');
});
Run Code Online (Sandbox Code Playgroud)