title: Spring MVC form http params to model object map member variable
body: <p>I struggled to name this question.  The problem I'm trying to solve is very similar to that described <a href="http://viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/" rel="nofollow">here</a> but instead of a list of beans I want to submit http request params that represent a map in the model object and let the framework (Spring) take care of building the map from the http request params.  Can anyone advise as to best practice/cleanest way to do this please?  Any help would be much appreciated.</p>
  
  <p>Currently I pass two String arrays that I then convert these into a map before saving into the model object.  I think there must be a nicer way to do this.</p>
  
  <p>I am using Spring MVC and Freemarker for view rendering.</p>
  
  <p>Illustrative code:</p>
  
  <p>model object:</p>
  
  <pre><code>public class Foo {
      private Map&lt;String, String&gt; barMap;
      // other member variables...
  }
  </code></pre>
  
  <p>View fremarker template:</p>
  
  <pre><code>&lt;#list foo.barMap?keys as currKey&gt;
      &lt;tr id="barList_${currKey_index}"&gt;
          &lt;td&gt;&lt;input name="key" type="text" value="${currKey}"/&gt;&lt;/td&gt;
          &lt;td&gt;&lt;input name="value" type="text" value="${foo.barMap[currKey]}"/&gt;&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/#list&gt;
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>@RequestMapping(value = "/foo", method = RequestMethod.POST)
  public String foo (Model model,
                     @RequestParam(value="key", required=false) String[] keys, 
                     @RequestParam(value="value", required=false) String[] values) {
  
      Foo foo = new Foo();
      Map&lt;String, String&gt; barMap = new HashMap&lt;String, String&gt;();
  
      if (keys != null &amp;&amp; values != null &amp;&amp; keys.length == values.length) {
          for (int i = 0; i &lt; keys.length; i++) {
              if (keys[i] != null 
                  &amp;&amp; !keys[i].isEmpty() 
                  &amp;&amp; values[i] != null 
                  &amp;&amp; !values[i].isEmpty()) {
  
                  barMap.put(keys[i], values[i]);
              }
          }
      }
  
      foo.setBarMap(map);
  
      return WebConstants.VIEW_FOO;
  }
  </code></pre>