21

在相同的上下文中,我有另一个查询

<select multiple="multiple" name="prodSKUs">
            <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
          <option value="${productSubCategoryList}"${productSubCategoryList == productSubCategoryName ? 'selected' : ''}>${productSubCategoryList}</option>
         </c:forEach>
        </select>

请求中的相应设置就像

for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    request.setAttribute("productSubCategoryName",productSubCategoryName);

}

在这里我有多个选择下拉菜单,即使我从 for 获得返回值作为两个,在 UI 中只有一个数据被突出显示,而不是第二个,代码有什么问题?

4

3 回答 3

29

假设您有一个集合 ${roles} 的元素要放入组合中,并且 ${selected} 是选定的元素,它会像这样:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

更新(下一个问题)

您正在覆盖属性“productSubCategoryName”。在 for 循环结束时,最后一个 productSubCategoryName。

由于表达语言的限制,我认为最好的处理方法是使用映射:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

然后在 JSP 中:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>
于 2010-04-21T11:55:45.123 回答
12

在 Servlet 中:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

然后在 JSP 中执行:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
    </c:forEach>
</select>

它将打印selectedHTML<option>元素的属性,因此您最终会像:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>
</select>

除了问题:这不是一个组合框。这是一个下拉菜单。组合框是可编辑的下拉菜单。

于 2010-04-21T12:00:21.940 回答
3

真的很简单。您只需要将字符串 'selected' 添加到正确的选项中。在下面的代码中, ${myBean.foo == val ? 'selected' : ' '} 如果选项的值与 bean 值相同,将添加字符串 'selected';

<select name="foo" id="foo" value="${myBean.foo}">
    <option value="">ALL</option>
    <c:forEach items="${fooList}" var="val"> 
        <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
    </c:forEach>                     
</select>
于 2014-08-18T19:00:06.767 回答