假设某一个类(如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 = 0;
int j = 0;
while ((len = input.read()) != -1) {
if (data == null) {
data = new byte[len];
}
input.read(data, 0, len);
table[i][j] = new String(data, 0, len, "UTF-8");
if (j == 0) {
j = 1;
} else {
i++;
j = 0;
}
}
}
input.close();
}
// 根据table中的数据转换字符串
public String convert(String str) {
if (table != null && str != null) {
for (String[] pair : table) {
str = str.replace(pair[0], pair[1]);
}
}
return str;
}
// 获取要转换的字符串
public String getText() {
return text;
}
// 设置要转换的字符串
public void setText(String text) {
this.text = text;
}
// 获取转换结果
public String getConvertedText() {
return convert(text);
}
}
用<jsp:useBean>获取request.setAttribute设置的对象(注意要设置scope="request"),然后用<jsp:setProperty>设置text属性,用<jsp:getProperty>读取convertedText。
<%
TextConverter tw = new TextConverter("zh-tw.bin");
request.setAttribute("converter", tw);
%>
<jsp:useBean id="converter" class="mypack.text.TextConverter" scope="request" />
<jsp:setProperty name="converter" property="text" value="很多人都认为圆神很可爱。" />
Property: <jsp:getProperty name="converter" property="convertedText" /><br />
当然,JSTL core标签库里面的<c:set>使用起来更简单,不需要事先声明。
<%
TextConverter cn = new TextConverter("zh-cn.bin");
request.setAttribute("converter2", cn);
%>
<c:set target="${converter2}" property="text" value="可愛的一顆小花生。" />
Property: ${converter2.convertedText}<br />