<jsp:setProperty>设置有参构造函数创建的自定义对象的属性

假设某一个类(如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 />

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巨大八爪鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值