使用JSTL在Select标签中填充的选定项目?

a k*_*a k 1 html java jsp jstl drop-down-menu

我使用JSP中的以下代码将生日月份存储在数据库中作为值.

<select name="birthday_month" id="birthday_month">
  <option value="-1">Month</option>
  <option value="1">Jan</option>
  <option value="2">Feb</option>
  ...
</select>
Run Code Online (Sandbox Code Playgroud)

在JSP中输出代码以使用我正在使用的JSTL显示以前选择的项目(这是不正确的)

<select name="birthday_month" id="birthday_month">
  <c:forEach var="value" items="${birthdaymonth}">
    <option value="${birthdaymonth}">${birthdaymonth}</option>
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    ...
  </c:forEach>
</select>
Run Code Online (Sandbox Code Playgroud)

What I am getting from this code is value like 1 or 2 in select tag

其他信息:

  1. 我在1月,2月,3月的数据库中存储了生日月份,如1,2,3 ..
  2. 我在Servlet中使用请求范围带来生日月的值
    request.setAttribute("birthdaymonth", user.getBirthdayMonth());

我在期待什么

  1. 当我显示以后的JSP时,它应该显示先前存储的生日月份为1月,2月,3月而不是1,2,3,并且还显示其他选项值,包括突出显示的所选项目.

Bal*_*usC 6

要动态迭代几个月的集合,您希望将月份存储Map<Integer, String>在密钥为月份编号的位置,值为月份名称.要<option>选择默认情况下创建HTML 元素,您需要设置该selected属性.

因此,假设您在范围内有a Map<Integer, String> months和a Integer selectedMonth,那么以下内容应该:

<select name="birthday_month">
    <c:forEach items="${months}" var="month">
        <option value="${month.key}" ${month.key == selectedMonth ? 'selected' : ''}>${month.value}</option>
    </c:forEach>
</select>
Run Code Online (Sandbox Code Playgroud)

条件运算符?:selectedselectedMonth等于当前迭代的月份数时打印.