2015-03-13 61 views
1

我正在開發一個使用JSP和Servlets的示例Web應用程序,在此應用程序中,我已經在Servlet中設置了一些對象,我可以使用request.getAttribute("Object")在JSP中檢索該值。這裏我想在JSP中迭代該數組的值。我怎麼能做到這一點,任何人都可以幫助我。如何檢索javascript/jsp中的Arraylist對象?

我的servlet代碼

ArrayList<Performer> Performerobj=new ArrayList<Performer>(); 
ResultSet rst = stm1.executeQuery("some query"); 
while (rst.next()) 
{ 
    Performer obj=new Performer(); 
    obj.setProject(projectname); 
    obj.setCount(rst.getString("COUNT")); 
    obj.setDate(rst.getString("DATE")); 
    obj.setEmpid(rst.getString("empid")); 
    Performerobj.add(obj); 
} 
request.setAttribute("Performer", Performerobj); 

Performer.java

public class Performer { 


private String project; 
private String empid; 
private String date; 
private String count; 

public String getProject() { 
    return project; 
} 
public void setProject(String project) { 
    this.project = project; 
} 
/*setter and getter...... for all*/ 

Perform.jsp

<% List<Performer>obj1=List<Performer>)request.getAttribute("Performerobj"); %> 
<script> 
     var obj=<%=obj1%> 
for(obj object : list) 
{ 
    /*IS it correct way or how can i iterate*/ 
} 
</script> 
+0

您是否收到任何錯誤?這裏是一個例子 - http://stackoverflow.com/questions/16397207/iterate-arraylist-in-jsp – 2015-03-13 10:49:41

+0

在jsp中,我可以使用這個選項,但在java腳本中,我該如何使用該方法? – 2015-03-13 11:19:14

回答

2

你可以做,如果你TR ansform的ArrayList對象爲使用庫像傑克遜JSON:

<% List<Performer>obj1 = (List<Performer>) request.getAttribute("Performerobj"); %> 
<script> 
var obj=<%=new ObjectMapper().writeValueAsString(obj1)%>; 
for(obj object : list) 
{ 
    /*IS it correct way or how can i iterate*/ 
} 
</script> 

另一種選擇是使用JSTL:

<c:forEach var="performer" items="${Performerobj}"> 
    <c:out value="${performer.project}"/> 
</c:forEach>