使用JSTL为JSP下拉选择的值

Jåc*_*cob 24 jsp jstl retain drop-down-menu

我在Servlet中有SortedMap来填充JSP中的下拉值,我有以下代码

    SortedMap<String, String> dept = findDepartment();
    request.setAttribute("dept ", dept);
Run Code Online (Sandbox Code Playgroud)

在JSP中

       <select name="department">
          <c:forEach var="item" items="${dept}">
            <option value="${item.key}">${item.value}</option>
          </c:forEach>
        </select>
Run Code Online (Sandbox Code Playgroud)

我正在使用一个JSP页面进行插入和更新.当我在编辑页面时,如何设置所选值以下拉选择值来自数据库的位置.

Bal*_*usC 41

在HTML中,所选选项由元素selected上的属性表示,<option>如下所示:

<option ... selected>...</option>
Run Code Online (Sandbox Code Playgroud)

或者,如果你是HTML/XHTML严格:

<option ... selected="selected">...</option>
Run Code Online (Sandbox Code Playgroud)

因此,您只需要让JSP/EL有条件地打印它.前提是您已按如下方式准备所选部门:

request.setAttribute("selectedDept", selectedDept);
Run Code Online (Sandbox Code Playgroud)

那应该这样做:

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
    </c:forEach>
</select>
Run Code Online (Sandbox Code Playgroud)

也可以看看:


小智 7

我尝试了 Sandeep Kumar 的最后一个答案,我发现方法更简单:

<option value="1" <c:if test="${item.key == 1}"> selected </c:if>>
Run Code Online (Sandbox Code Playgroud)