Spring在表单中添加默认值:jsp中的选项

时间:2015-11-10 18:56:22

标签: java jsp spring-mvc

是否可以在我的下拉列表中选择一些默认值,该列表位于我的.jsp中,如下所示:

<div class="form-group">
   <form:label path="month">Select month</form:label>
   <form:select path="month" class="form-control">
   <form:options items="${months}" />
   </form:select>
</div> 

在我的控制器中我有方法:

private List<String> getMonths() {
    List<String> months = new ArrayList<String>();
    months.add("January");
    months.add("February");
    months.add("March");
    months.add("April");
    months.add("May");
    months.add("June");
    months.add("July");
    months.add("August");
    months.add("September");
    months.add("October");
    months.add("November");
    months.add("December");
    return months;
}

并将其添加到.jsp中,如下所示:

model.addAttribute("months", getMonths()); 

我需要在加载页面后预先选择一些值,例如。 “游行”。

1 个答案:

答案 0 :(得分:1)

您需要使用forEach遍历列表,然后使用if condition选择您想要选择的默认月份。见下面的样本:

<c:choose>
    <c:forEach items="${months}" var="month">
        <c:when test="${month == 'March'}">
            <option value="${month}" selected>${month}</option>
        </c:when>
        <c:otherwise>
          <option value="${month}">${month}</option>
        </c:otherwise>
    </c:forEach>
  </c:choose>