JSP访问列表中对象的方法

时间:2013-07-04 08:24:38

标签: java jsp object arraylist

我有2个java类。一个是java bean,另一个是来自这个java bean类的实例集合。

public class Quiz{ 
  private int id;
  private String title;
  //getters and setters 
}

public class Quizzes{
  List<Quiz> quizList = new ArrayList<Quiz>;
  public Quizzes{
    //constructor to add Quiz objects to quizList
    Quiz curQuiz = new Quiz();
    ...
  }
  public List<Quiz> getQuizList(){
    return this.quizList;
  }

}

在我的JSP中,我想访问例如测验的id(或标题)。我怎样才能做到这一点?我唯一的想法是遍历quizlist中的Objects并调用getId Method,然后将此Integer值添加到List中。例如:

public List<Integer> getId(){
    List<Integer> idList = new ArrayList<Integer>();
    ListIterator<Quiz> ir = quizlist.listIterator();
    int id;
    while (ir.hasNext()){
        Quiz curQuiz = ir.next();
        id = curQuiz.getId();
        idList.add(id);
    }
    return idList;
}

但是没有更好的解决方案吗?

2 个答案:

答案 0 :(得分:3)

您可以查看<jsp:useBean>标记。相同的语法是

<jsp:useBean id= "attributeName" scope= "page | request | session | application" class= "yourPackage.yourClass"> </jsp:useBean>.

此处attributeName是您在page, request, session or application scope中设置的属性的名称。 yourPackage.yourClass是您的beanClass,如果您想访问Quiz成员变量,则为Quiz

你可以找到好的例子here

如果要迭代jsp中可访问的列表,则可以使用forEach标记。

<c:foreach jsp iterate over list

<c:forEach var="window" items="${requestScope.quizList}">
    <c:out value="${quiz.id}"/> 
    <c:out value="${quiz.name}"/>
</c:forEach>

答案 1 :(得分:0)

如果你只需要每个测验的Id,你可以在测验中覆盖toString()函数:

public class Quiz{ 
  private int id;
  private String title;
  //getters and setters 
}

public class Quizzes{
  List<Quiz> quizList = new ArrayList<Quiz>;
  public Quizzes{
    //constructor to add Quiz objects to quizList
    Quiz curQuiz = new Quiz();
    ...
  }
  public List<Quiz> getQuizList(){
    return this.quizList;
  }

   @Override 
   public String toString(){
return getId();
  }

}

这样当你调用toString()时,它将返回相应的Id:

Quiz.toString(); 

您可以将迭代更改为:

public List<Integer> getId(){
    List<Integer> idList = new ArrayList<Integer>();
    ListIterator<Quiz> ir = quizlist.listIterator();
    while (ir.hasNext()){
        idList.add(ir.next().toString());
    }
    return idList;
}