代码改变世界

在jsp中接收并处理servlet传过来的含有bean的List

2017-03-07 20:04  Self_made  阅读(3347)  评论(0编辑  收藏  举报

在jsp中接收并处理servlet传过来的含有bean的List

例如有以下bean

package com.test.domain;
class Student{
	private Stirng name;
	private int age;
	
	public Student(String name, int age){
		this.name = name;
		this.age = age;
	}

	public String getName(){
		return this.name;
	}

	public void setName(Stirng name){
		this.name = name;
	}

	public int getAge(){
		return this.age;
	}

	public void setAge(int age){
		this.age = age;
	}
}  

在Servlet中有如下代码:

List<Student> stuList = new ArrayList<Student>();
stuList.add(new Student("Tom", 19));
stuList.add(new Student("Jerry", 20));
request.setAttribute("stuList", stuList);

在jsp中接收并处理传过来的stuList:

首先在jsp中导入Student的包如下:

<%@ page import= "com.test.domain.Student"%>    

在JavaScript中通过如下方式处理:

<script type="text/javascript">
	var stuName = new Array();
	<% int i=0;List<Student> stuList = (List<Student>) request.getAttribute("stuList");
	   for(i = 0; i < stuList.size(); i ++) { %>
			stuName[<%=i%>] = <%=((Student) stuList.get(i)).getName()%>;				
	<% } %>
</script>