Search code examples
javajspstruts2ognl

How to check list.contains in jsp using struts 2 tags


I need to show a series of check boxes and if a condition is succeeded, I need to check them. Below is my code. I have regions which is a hashmap and SelectedRegions which is an array list. I am iterating over my regions map, and displaying checkboxes with text next to it as the value from my regions map. Now, while iterating, if the value of regions map is available in the array list, I need to make the check box checked. else Un checked. I tried like the one shown below. But its not working.

<s:iterator value="regions">
    <li>
        <div class="listClass">
            <s:if test="#regions.value==selectedRegions.value">
                <input type="checkbox" id='myTheater' checked="checked" name="theaterCheckBox" class="theaterCheckBox" />
                <s:property value="value" />
            </s:if>
            <s:else>
                <input type="checkbox" id='myTheater' name="theaterCheckBox" class="theaterCheckBox" />
                <s:property value="value" />
            </s:else>
        </div>
        <div class="checkboxDiv">
            <input type="checkbox" id="allFeatured" class="featuredCheckBox" />
        </div>
    </li>
</s:iterator>

Some how, the if condition that I am using is not working. Could you please let me know how to attain this?


Solution

  • There are really many ways to do this. You should also check out the <s:checkbox/> and <s:checkboxlist/> tags;

    Also note that to follow DRY, you could put the <s:if> around the checked="checked" part only, since all the rest is the same.

    Keeping it simple, with your code as-is, one way consists in using OGNL's in (contains) and OGNL's {} (list projection) like follows:

    <s:iterator value="regions">
        <li>
            <div class="listClass">
    
                <input type = "checkbox" 
                         id = "myTheater" 
    <s:if test="%{value in selectedRegions.{value}}">
                    checked = "checked"
    </s:if>
                       name = "theaterCheckBox" 
                      class = "theaterCheckBox" />
    
                <s:property value="value" />
            </div>
            <div class="checkboxDiv">
                <input type="checkbox" id="allFeatured" class="featuredCheckBox" />
            </div>
        </li>
    </s:iterator>