Search code examples
javajspselectstruts2ognl

<s:select> with dynamic list name


I want to iterate over a list of strings containing names for <s:select> list source, but the HTML output is not as expected : it's the name of the list that is display, not the content.

My Action code:

public class DescriptionTabArchiveAction extends ActionSupport {
    private List<String> vegetables = new ArrayList<String>();
    private List<String> devices = new ArrayList<String>();

    // contain "vegetables" and "devices".
    private List<String> selectList = new ArrayList<String>();

    @Action("multipleSelect")
    public String multipleSelect() {
                vegetables.add("tomato");
                vegetables.add("potato");

                devices.add("mouse");
                devices.add("keyboard");

                selectList.add("vegetables");
                selectList.add("devices");

        return SUCCES;
    }

       // getters and setters
}

JSP:

<s:iterator value="selectList" var="listName">

    <s:select list="%{#listName}" />

    <!-- I tried with this line too : same behaviour. -->
    <%-- <s:select list="#listName" /> --%>
</s:iterator>

What I get (html ouput):

<select name="" id="">
    <option value="vegetables">vegetables</option>
</select>
<select name="" id="">
    <option value="devices">devices</option>
</select>

What I expect (html output):

<select name="" id="">
    <option value="tomato">tomato</option>
    <option value="potato">potato</option>
</select>
<select name="" id="">
    <option value="mouse">mouse</option>
    <option value="keyboard">keyboard</option>
</select>

My Question:

How can I dynamically iterate over a list of string to have multiple <s:select> with different list source?


Solution

  • Use a Map instead of List

    private Map<String, List<String>> selectMap = new HashMap<>();
    //getter and setter here
    
    @Action("multipleSelect")
    public String multipleSelect() {
        vegetables.add("tomato");
        vegetables.add("potato");
    
        devices.add("mouse");
        devices.add("keyboard");
    
        selectMap.put("vegetables", vegetables);
        selectMap.put("devices", devices);
    
        return SUCCESS;
    }
    

    modify iterator to use a map

    <s:iterator value="selectMap">    
        <s:select list="%{value}" />
        ...
    </s:iterator>