我正在开发一个简单的Web应用程序,我想在下一个JSP页面的HTML页面中选择下拉列表的选项标签。我使用MVC模式,因此Servlet作为控制器将重定向(转发?)请求到JSP视图。如何从下拉列表中选择选项标签?
request.getParameter()
仅给出了选项值。但在我的情况下,期权价值和标签是不同的。我如何获得选项标签?
我正在开发一个简单的Web应用程序,我想在下一个JSP页面的HTML页面中选择下拉列表的选项标签。我使用MVC模式,因此Servlet作为控制器将重定向(转发?)请求到JSP视图。如何从下拉列表中选择选项标签?
request.getParameter()
仅给出了选项值。但在我的情况下,期权价值和标签是不同的。我如何获得选项标签?
您需要在服务器端维护选项值和标签的映射。例如。里面的一些ServletContextListener
或者是servlet的init()
:
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
这样,您就能够获得:
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}
,那么你可以用下列方式显示它在服务器侧标记如下:
Map<String, String> countries = (Map<String, String>) getServletContext().getAttribute("countries");
// ...
String countryCode = request.getParameter("country");
String countryName = countries.get(countryCode);
// ...
或者在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>
非常感谢编辑和回答问题......我有点困惑如何把我的问题..我们不能写一个单独的下拉框POJO和访问选定的值使用
这可以在不存储在服务器端的东西来完成。
<select name="menu" id="menu">
<option value="1">label 1</option>
<option value="2">label 2</option>
</select>
<button onclick='show()'>Click me</button>
<script type="text/javascript">
function show(){
var theContents = document.getElementById('menu')[document.getElementById('menu').selectedIndex].innerText;
window.alert(theContents);
}
</script>
您无法从JSP中取回它。您必须按照BalusC的答案建议的方式维护一个映射。 – 2012-01-12 20:35:44
@XCoder:我们可以为下拉框编写一个单独的POJO,并使用,,访问在下一个JSP页面上选择的值。可能吗?请回复..谢谢 –
2012-01-13 05:45:23