如何从下拉列表中获取选定的选项标签? [英] How get selected option label from a dropdown list?

查看:33
本文介绍了如何从下拉列表中获取选定的选项标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的 web 应用程序,我想在下一个 JSP 页面的 HTML 页面中获取下拉列表的选项标签.我正在使用 MVC 模式,因此作为控制器的 Servlet 将重定向(转发?)请求到 JSP 视图.

I am developing a simple web application in which I want to take the option label of a dropdown list in HTML page on the next JSP page. I am using MVC pattern and thus Servlet as a controller will be redirecting (forwarding?) the request to JSP view.

request.getParameter() 只给我选项值.但在我的情况下,选项值和标签是不同的.如何获取选项标签?

The request.getParameter() gives me only the option value. But in my case the option value and label are different. How can I get the option label?

推荐答案

您需要在服务器端维护一个选项值和标签的映射.例如.在一些 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>

或预先选择下拉列表:

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

这篇关于如何从下拉列表中获取选定的选项标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆