假設某一個類(如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 />