这是一个获取下拉列表项的方法,能够输出所有的列表项,但在jsp页面时却只能显示最后一项
public List<Type> loadPetsType() throws Exception
{
List<Type> list = null;
sql = "SELECT  ID, TYPENAME FROM Type ";
try
{
this.pst = this.conn.prepareStatement(sql);
ResultSet rs = this.pst.executeQuery();
while (rs.next())
{
list = new ArrayList<Type>();
type = new Type();
type.setTypeId(rs.getInt(1));
System.out.println(type.getTypeId() + " ");
type.setTypeName(rs.getString(2));
System.out.println(type.getTypeName() + "  ");
list.add(type);
}
} catch (Exception e)
{
throw e;
} finally
{
if (this.pst != null)
{
try
{
this.pst.close();
} catch (Exception e)
{
throw e;
}
}
}
return list;
}jsp页面代码:
<select name="select" class="Common">
<%
List<Type> list = null;
try
{
list = DAOFactory.getIPetsDAOInstance().loadPetsType();
request.setAttribute("typeList", list);
%>
<c:forEach items="${typeList}" var="type">
<option value="${type.typeId}">
${type.typeName }
</option>
</c:forEach>
<%
} catch (Exception e)
{
e.printStackTrace();
}
%>
</select>
请问这是怎么回事?
输出如下:

宠物小狗  

宠物小猪  

宠物小猫  

宠物兔  

宠物鼠  

宠物猴  

宠物蛇  
16 
宠物 
jsp页面只显示16 宠物

解决方案 »

  1.   

    没看出来问题,你页面上直接右键查看源代码,有生成option么?
      

  2.   

    我就是奇怪,在Java方法里面能输出来,但在页面上就只显示最后一项
      

  3.   

    list = new ArrayList<Type>();放到while外面去。
      

  4.   

    list = new ArrayList<Type>(); 你每次都生成一个新的列表。
      

  5.   

    问题的根源是,你初始化是在while循环内,每一次循环都初始化一次,list存放的是最后一次循环的一条记录(也就是最后一条记录)
    解决方法:就是3楼的方法,list初始化在while循环之前。
      

  6.   

    每次你都重新NEW了一个LIST...也就是它 list = new ArrayList<Type>();
    放在while上面。。
      

  7.   

    每次你都重新NEW了一个LIST...也就是它 list = new ArrayList<Type>();
    放在while上面。。
      

  8.   

    每次你都重新NEW了一个LIST...也就是它 list = new ArrayList<Type>();
    放在while上面。。
      

  9.   

    List<Type> list = new ArrayList<Type>();
    sql = "SELECT ID, TYPENAME FROM Type ";
    try
    {
    this.pst = this.conn.prepareStatement(sql);
    ResultSet rs = this.pst.executeQuery();
    while (rs.next())
    {
    .....................
      

  10.   

    List<Type> list = new ArrayList<Type>();
    sql = "SELECT ID, TYPENAME FROM Type ";
    try
    {
    this.pst = this.conn.prepareStatement(sql);
    ResultSet rs = this.pst.executeQuery();
    while (rs.next())
    {
    .....................
      

  11.   

    List<Type> list = new ArrayList<Type>();
    sql = "SELECT ID, TYPENAME FROM Type ";
    try
    {
    this.pst = this.conn.prepareStatement(sql);
    ResultSet rs = this.pst.executeQuery();
    while (rs.next())
    {
    .....................