Selected item populating in Select tag using JSTL?

2020-06-29 11:28发布

问题:

I store Birthday Month in database as value using following code in JSP.

<select name="birthday_month" id="birthday_month">
  <option value="-1">Month</option>
  <option value="1">Jan</option>
  <option value="2">Feb</option>
  ...
</select>

Output code in JSP to show previously selected item using JSTL that I am using (which is not correct)

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

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

Other Information:

  1. I store birthday month as value like 1,2,3.. for Jan,Feb,Mar... in Database
  2. I bring value of birthday month in request scope in Servlet using
    request.setAttribute("birthdaymonth", user.getBirthdayMonth());

What i was expecting

  1. When i show later JSP it should show previously stored birthday month as Jan,Feb, Mar and not 1,2,3 and also show other Option values including selected item as highlighted.

回答1:

To dynamically iterate over a collection of months, you'd like to store the months in a Map<Integer, String> where the key is the month number and the value is the month name. To make a HTML <option> element by default selected, you need to set the selected attribute.

So, assuming that you have a Map<Integer, String> months and a Integer selectedMonth in the scope, then the following should do:

<select name="birthday_month">
    <c:forEach items="${months}" var="month">
        <option value="${month.key}" ${month.key == selectedMonth ? 'selected' : ''}>${month.value}</option>
    </c:forEach>
</select>

The conditional operator ?: will print selected when the selectedMonth is equal to the currently iterated month number.