且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从下拉列表中选择选项标签?

更新时间:2022-05-23 22:41:13

您需要在服务器端维护选项值和标签的映射。例如。里面一些 ServletContextListener 或者servlet的 init()

You need to maintain a mapping of option values and labels in the server side. E.g. inside some ServletContextListener or perhaps servlet's init():

Map<String, String> countries = new LinkedHashMap<String, String>();
countries.put("CW", "Curaçao");
countries.put("NL", "The Netherlands");
countries.put("US", "United States");
// ...

servletContext.setAttribute("countries", countries);

当您将其作为 $ {countries} ,那么你可以显示如下:

When you put it in the application scope as ${countries}, then you can display it as follows:

<select name="country">
  <c:forEach items="${countries}" var="country">
    <option value="${country.key}">${country.value}</option>
  </c:forEach>
</select>

这样您就可以在服务器端获取标签,如下所示:

This way you will be able to obtain the label in the server side as follows:

Map<String, String> countries = (Map<String, String>) getServletContext().getAttribute("countries");
// ...

String countryCode = request.getParameter("country");
String countryName = countries.get(countryCode);
// ...

或在JSP中显示纯文本:

Or to display plain in JSP:

<p>Country code: ${param.country}</p>
<p>Country name: ${countries[param.country]}</p>

或者预先选择下拉列表:

Or to pre-select the dropdown:

<select name="country">
  <c:forEach items="${countries}" var="country">
    <option value="${country.key}" ${param.country == country.key ? 'selected' : ''}>${country.value}</option>
  </c:forEach>
</select>