網上看到的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>