<s:select> with dynamic list name </s:select>

时间:2013-12-13 17:13:36

标签: java jsp select struts2 ognl

我想迭代一个包含<s:select>列表源名称的字符串列表,但HTML输出不符合预期:它是显示列表的名称,而不是内容

我的Action代码:

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>

我得到了什么(html输出):

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

我的期望(html输出):

<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>

我的问题:

如何动态迭代字符串列表以使多个<s:select>具有不同的列表源?

1 个答案:

答案 0 :(得分:5)

使用Map代替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;
}

修改迭代器以使用地图

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