Search code examples
javajspstruts2scriptletstruts-tags

How to set end attribute dynamically with Struts2 iterator in JSP


<% 
    RegisterAction aro=new RegisterAction();    
    int count=aro.getLi().size();
%>

<s:iterator value="li" begin="0" end="1">
    <fieldset>
        name     : <s:property value="name"     /><br/>
        password : <s:property value="password" /><br/>
        email    : <s:property value="email"    /><br/>
        gender   : <s:property value="gender"   /><br/>
        country  : <s:property value="country"  /><br/>
    </fieldset>
</s:iterator>

How to set end attribute value dynamically for iteration, reading the count variable ?

If I use end="<%=count%>" this is not working.

If I use end="count" it's working but I am getting same result multiple of numbers if I refresh the page or reload.


Solution

  • You can use the #attr notation in OGNL to read variables set within Scritplet blocks, if you push them in the pageContext:

    <% 
        RegisterAction aro = new RegisterAction();
        int count = aro.getLi().size();
        pageContext.setAttribute("count", count); // pushing the variable into the pageContext
    %>
    
    <s:iterator value="li" begin="0" end="%{#attr['count']}">
        <fieldset>
            name     : <s:property value="name"     /><br/>
            password : <s:property value="password" /><br/>
            email    : <s:property value="email"    /><br/>
            gender   : <s:property value="gender"   /><br/>
            country  : <s:property value="country"  /><br/>
        </fieldset>
    </s:iterator>
    

    But you should never use Scriptlet for many reasons.

    It's also very easy to use Struts tags instead of scriptlets for your purposes, like shown in this answer.


    EDIT:

    If I use end="count" it's working but I am getting same result multiple of numbers if I refresh the page or reload.

    It's however unclear why you are instantiating an Action in a Scriptlet block, and then why you do expect the result of count to be different across the page loadings, since your code is always referring to a collection in its initial state.

    If RegisterAction is your current action, then what you want is probably:

    <s:iterator value="li" begin="0" end="%{li.size()}">
    

    that is in fact

    <s:iterator value="li">
    

    and you are overcomplicating a simple iteration by factor 2337.