سؤال

In the official Struts2 documentation I find the following snippet of code:

<s:iterator value="{1,2,3,4,5}" begin="2" end="4" >
   <!-- current iteration value (2,3,4) -->
   <s:property value="top" />
</s:iterator>

This iterates over the values 1 to 5. From that example, I thought any string between {} brackets would be considered as an array.

I have a variable in Struts2 set to contain a string value similar to the one above, but the iterator always sees it as 1 element rather than an array of elements. None of the examples below work as intended. I used all different combinations of %{#}.

<s:set var="testa">{6,7,8,9,10}</s:set>
<s:iterator value="testa">
    <!-- <s:property/> -->
</s:iterator>

<s:set var="testb">{A,B,C,D,E}</s:set>
<s:iterator value="#testb">
    <!-- <s:property/> -->
</s:iterator>

<s:set var="testc">{F,G,H,I,J}</s:set>
<s:iterator value="%{#testc}">
    <!-- <s:property/> -->
</s:iterator>

<s:set var="testd">{K,L,M,N,O}</s:set>
<s:iterator value="%{testd}">
    <!-- <s:property/> -->
</s:iterator>

what I expected as outcome was:

<!-- 6 -->
<!-- 7 -->
<!-- 8 -->
<!-- 9 -->
... and so on

But what I really got was:

<!-- {6,7,8,9,10} -->
<!-- {A,B,C,D,E} -->
... and so on

what am I doing wrong?

Please note I'm not looking for ways to iterate over a list of java objects (I know how to do this), I really want to iterate over a textual representation of an array.

هل كانت مفيدة؟

المحلول

Any string enclosed in the brackets remains the string until this string is parsed for OGNL expression. In the first example the string enclosed with brackets evaluated as OGNL expression that returns a list. This list is iterated and results are printed. Struts tags parse for OGNL expressions only in tag's attributes, so it doesn't parse for tag body. if you need to parse in the tag body, you can use a property tag. So all attempts to treat a string as list failed. The iterator tag accepts only a collection of java objects and cannot iterate a string, because a string doesn't have an iterator.

I really want to iterate over a textual representation of an array

So this is only possible if you convert a textual representation to an array. The iterator tag can iterate over arrays.

<s:set var="testa">{6,7,8,9,10}</s:set>
<s:iterator value="%{#testa.replaceAll('[\\\{\\\}]','').split(',')}">
    <!-- <s:property/> -->
</s:iterator>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top