目录

利用JSP代码段动态生成表格,表格数据来自内存中的数组或集合类容器(List、Map、Set)

①编写实体类bean/Student.java

package bean;

public class Student {
	private String no;
	private String name;
	private String tel;
	public Student() {};
	public Student(String no,String name,String tel){
		this.no = no;
		this.name = name;
		this.tel = tel;
	}
	public String getNo() {
		return no;
	}
	public void setNo(String no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
}

②从数组和List容器中取出数据放入表格中

table.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page import="bean.Student"%>

<html>
  <head>
    <title>table</title>
  </head>
  <body>
  	<%
  	//数组中预先准备好数据
	Student[] stu = {new Student("001","pjt","15618919819"),
				     new Student("002","cxl","17722533733"),
					 new Student("003","fyx","14515722279") };
	//List中预先准备好数据
	List<Student> lstu = new ArrayList<Student>();
	lstu.add(new Student("004","gg","14227189198"));
	lstu.add(new Student("005","tt","18618988966"));
	lstu.add(new Student("006","ddf","14728722874"));
    %>
    <%-- 从数组中取出数据放入表格中 --%>
    <table border="1" bgcolor="#aa8899">
    	<tr><td>学号</td><td>姓名</td><td>联系电话</td></tr>
    	<%
    		for(int i=0; i<stu.length;++i) {
    	%>
    	 <tr>
    	 	<td><%=stu[i].getNo() %></td>
    	 	<td><%=stu[i].getName() %></td>
    	 	<td><%=stu[i].getTel() %></td>
    	 </tr>
    	 <% } %>
    </table>
    <%-- 从List中取出数据放入表格中(学号带超链接) --%>
    <table border="1" bgcolor="#aaff77">
    	<tr><td>学号</td><td>姓名</td><td>联系电话</td></tr>
    	<%
    		for(int i=0;i<lstu.size();++i) {
    	 %>
    	 <tr>
    	 	<td><a href=detail.jsp?no=<%=((Student)lstu.get(i)).getNo()%>>
    	 		<%=((Student)lstu.get(i)).getNo()%></a>
    	 	</td>
    	 	<td><%=((Student)lstu.get(i)).getName()%></td>
    	 	<td><%=((Student)lstu.get(i)).getTel()%></td>
    	 </tr>
    	 <% } %>
    </table>
  </body>
</html>

③超链接跳转页面的处理

detail.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<html>
  <head>
    <title>detail.jsp</title>
  </head>
  <body>
    <%
    	String no = request.getParameter("no");
     %>
     学号为<font size=4 color="red"><%=no%></font>同学的详细信息如下<br>
  </body>
</html>

效果 

点击学号"004"后的效果 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐