Bind map (key and value) to spring form in jsp

I have a class like this:

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

I need a form in which a user can add pairs of key values ​​to a property map. All the SO answers I found on this just show how to use the already known key to enter a value using:

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

How can I make the key editable? I'm kind of ...

<form:input path="properties.key" /><form:input path="properties.value" />
+4
source share
1 answer

I got this job and I had to find this page again to provide my answer.

<form>, . , name .

, JQuery /. , , JQuery, , , .

, 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 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+']');
});
0

All Articles