网上看到的javabean的代码都比较简单只是返回简单的String,但是实际使用中有时候可能会有需要一次返回多条数据的情况,下面例子就是使用List返回多条数据的例子,以此类推像dataset,table之类的数据应该也是可以这样得到的
javabean的代码,为了方便直接写的固定数据firstname
package com.myapp.struts;
import java.beans.*;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
public class NewBean implements Serializable {
public static final String PROP_SAMPLE_PROPERTY = "sampleProperty";
private List<String> firstname;
private String sampleProperty;
private PropertyChangeSupport propertySupport;
public NewBean() {
propertySupport = new PropertyChangeSupport(this);
}
public String getSampleProperty() {
return sampleProperty;
}
public void setSampleProperty(String value) {
String oldValue = sampleProperty;
sampleProperty = value;
propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY, oldValue, sampleProperty);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
public List<String> getFirstname() {
List<String> l = new LinkedList<String>();
l.add("1");
l.add("2");
return l;
}
public void setFirstname(List<String> firstname) {
this.firstname = firstname;
}
}
使用javabean的jsp页面,在写class的时候开始写的是NewBean总是找不到这个类,后来改成包含命名空间的全名才可以
<%@page import="com.myapp.struts.NewBean"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="test1" class="com.myapp.struts.NewBean" scope="page"/>
<c:forEach var="student" items="${test1.firstname}">
<p>
${student}
</p>
</c:forEach>
<h1>Hello World!</h1>
</body>
</html>