【问题标题】:show the selected value in dropdown on edit jsp page on page load (Spring MVC)在页面加载时编辑 jsp 页面的下拉列表中显示所选值(Spring MVC)
【发布时间】:2014-05-24 05:45:12
【问题描述】:
我想在页面加载时的下拉列表中显示所选值。
我的编辑页面显示一个值,国家。现在用户属于美国,所以在页面加载时应该默认选择美国。我可以使用 javascript 或 jquery。
我在互联网上找到的帮助很少,但它们是与 scriplet () 相关的,我不想使用它们。
我正在传递一个具有 Id 和 Value 的列表。我在另一个对象中也有 Id。
我可以通过在 jsp 中引入一个 for 循环并显示值来编写代码,但可能是我在那里犯了一些错误。也想知道是否有更好的方法来做到这一点。
我正在使用 Spring MVC。
谢谢。
【问题讨论】:
标签:
javascript
jquery
spring
jsp
spring-mvc
【解决方案1】:
“现在用户属于美国,所以在页面加载时应该默认选择美国。”。您事先知道用户属于某个国家/地区。
假设你有一个 pojo 国家:
public class Country{
String countryName;
String countryId;
//setters and getters
}
public class YourForm{
List<Country> countryList;
String selectedCountryId;
...
//setters and getters
}
在委托给 jsp 的控制器方法中:
...
YourForm form = new YourForm();
//set your countrylist to form
//set country user belongs to - selectedCountryId - since you know before hand user belongs to some country.
model.addAttribute("yourForm", form):
...
现在在jsp中访问它:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
</head>
<body>
<form:form id="yourForm" modelAttribute="yourForm" method="post">
<tr>
<td width="50%" class="label">
<form:select id="countryId" path="selectedCountryId" title='Select Country'>
<option value="">Please Select</option>
<form:options items="${countryList}" itemValue="countryId" itemLabel="countryName"/>
</form:select>
</td>
</tr>
</body>
由于 selectedCountryId 已在控制器中设置,您将在 jsp 中看到该国家/地区自动选择。