问题
In SQL Server database I have a table which has three columns namely Ref_Name,Ref_from and Ref_to.Now I want a dropdown list to hold values row-wise i.e all column values of the row should be in the dropdown list in following way:-
Reference-1(2014-10-10 07:17:00.000 to 2014-10-10 08:46:00.000)
Reference-2(2014-09-01 10:00:00.000 to 2014-09-01 11:00:00.000)
For this I have used LinkedHashMap as:-
public LinkedHashMap<String, List<String>> connect()
{
ArrayList<String> list = new ArrayList<String>();
try
{
con = getConnection();
stmt = con.createStatement();
String sql="select Ref_No,From_Date,To_Date from Ref_time";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while (rs.next())
{
list.add(rs.getString(2));
list.add(rs.getString(3));
ref.put(rs.getString(1), list);
}
}
catch( Exception e )
{
System.out.println("\nException "+e);
}
finally
{
//closeConnection(stmt, rs, con);
}
return ref;
}
When I use it in jsp as
<select name="ref_logtime">
<c:forEach var="aff" items="${obj.connect()}">
<option value="${aff.key}">${aff.key}</option>
<option value="${aff.value}">${aff.value}</option>
</c:forEach>
</select>
Then in dropdown ,I get values as:-
Reference-1
All datetime entries are shown here
Reference-2
All datetime entries are shown here
But I want my dropdown list to have values row wise.How to do that?
回答1:
There are two problems with your code. First, every reference mapping needs to have its own List
. Currently, the list is being shared and hence both the reference entries would show all the dates. Change the code as
rs = stmt.executeQuery(sql);
while (rs.next())
{
List<String> list = new ArrayList<String>();
list.add(rs.getString(2));
list.add(rs.getString(3));
ref.put(rs.getString(1), list);
}
The second problem is with the JSTL tag. You need only one <option>
tag within the loop which would run twice for you (because you have two reference entries coming from the database) to generate the two <option>
tag entries.
<select name="ref_logtime">
<c:forEach var="aff" items="${obj.connect()}">
<option value="${aff.key}">${aff.key} ${aff.value}</option>
</c:forEach>
</select>
来源:https://stackoverflow.com/questions/28407312/how-to-populate-the-dropdown-list-from-sql-server-database-using-linkedhashmap-i