假设某一个类(如TextConverter类)有一个无参构造函数和一个有参构造函数,我们可以在Servlet里面先用有参构造函数自己new一个对象出来,存到request.setAttribute里面去。
Servlet转发到jsp页面后,再在jsp页面上用<jsp:useBean scope="request">获取刚才用有参构造函数创建出来的自定义对象,然后用<jsp:setProperty>和<jsp:getProperty>存取对象的属性值。
例如:
package mypack.text;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class TextConverter {
private String[][] table;
private String text;
// 无论是否用到,JavaBean必须要有一个无参的构造函数
public TextConverter() {
}
// 有参构造函数:从文件中读取table数据
public TextConverter(String fileName) throws IOException {
FileInputStream fileInput = new FileInputStream(fileName);
DataInputStream input = new DataInputStream(fileInput);
int len = Integer.reverseBytes(input.readInt());
if (len > 0) {
table = new String[len][2];
byte[] data = null;
int i