开发者

Binding a variable collection inside a Spring enabled Velocity template

开发者 https://www.devze.com 2023-03-28 19:39 出处:网络
Suppose I have the following form backing object for a Velocity 1.5 template: publi开发者_StackOverflow社区c class Bucket {

Suppose I have the following form backing object for a Velocity 1.5 template:

publi开发者_StackOverflow社区c class Bucket {

    String data1;
    String data2;
    String data3;
    String data4;

    // getters setters blah blah...
}

I'd like to bind these four String attributes to the following java.util.Map of Strings, inside four drop down single select controls:

"a" : "1"
"b" : "2"
"c" : "3"
"d" : "4"

If inside my page's controller Model, I name the backing object "boData", and the value map "labelKeys", velocity can bind the backing object's properties for me:

#springFormSingleSelect( "boData.data1" $labelKeys "")
#springFormSingleSelect( "boData.data2" $labelKeys "")
#springFormSingleSelect( "boData.data3" $labelKeys "")
#springFormSingleSelect( "boData.data4" $labelKeys "")

However, is there a way to avoid invoking #springFormSingleSelect four times? I mean, there's a pattern here, but I can't see the way to express it in Velocity's terms.

If for example, I defined instead these four String attributes inside class Bucket as a Java array, or a java.util.List, how could I tell velocity that I need it to bind a drop down single select control for each element in the List?

public class Bucket {
    List<String> dataItems = new ArrayList<String>();
    // getter, setter...
}

I thank you for any insight you could provide!


I am not sure if the answer was clear. Trying to explain Spring velocity binding requires the entire path as an argument to the #springBind So If you have a collection dataItems, you cannot bind like

    #foreach($dataItem in $dataItems)
      #springFormSingleSelect( "dataItem.data1" $labelKeys "")
    #end

Instead

    #set ($end = $dataItems.size() - 1)
    #foreach($i in [0..$end])
      #springFormSingleSelect( "dataItems[$i].data1" $labelKeys "")
    #end

This would bind the collection items.


How about:

#foreach($i in [1..4])
    #set($field = "boData.data" + $i)
    #springFormSingleSelect($field $labelKeys "")
#end


Not sure if I understand the question. But seems like all you need is a foreach loop. In Velocity you can type java as well if that makes your life easier.

However you can do something like:

#set ($map = $myobject.getMap() )
#foreach ($mapEntry in $map.entrySet())
     // $mapEntry.key
     // $mapEntry.value
    #springFormSingleSelect( "boData.data1" $mapEntry.key "")
#end

You can do the same with a list.

I hope this helps. Regards,

0

精彩评论

暂无评论...
验证码 换一张
取 消