java 自定义标签(一)

2014-11-24 09:17:10 · 作者: · 浏览: 0
1、编写**.tld文件
[html]
< xml version="1.0" encoding="UTF-8" >
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web- jsptaglibrary_2_0.xsd"
version="2.0">
1.0
candy
/candy
带遮罩的网页对话框标签
msgdialog
candy.tld.MsgDialogTag
scriptless
对话框标题文字,默认为"温馨提示"
title
false
true
遮罩的高度,默认为屏幕的高度,即100%
height
false
true
对话框的顶部距离,默认为300px
top
false
true
对话框的宽度,默认为500px
boxwidth
false
true
基本URL
basepath
true
true
临时ID后缀,避免ID冲突,默认为系统时间的毫秒数
tmpid
false
true
2.编写工具类
[java]
package candy.tld;
import java.io.*;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/** 带遮罩的网页对话框自定义标签类 */
public class MsgDialogTag extends SimpleTagSupport {
String title = "温馨提示"; // 对话框标题文字
String height = "100%"; // 遮罩的高度,默认为屏幕的高度,即100%
String top = "300px"; // 对话框的顶部距离,默认为100px
String boxwidth = "330px";// 对话框的宽度,默认为500px
String basepath = ""; // 基本URL
String tmpid = null; // 临时ID后缀,避免ID冲突,默认为系统时间的毫秒数
/** 标签体处理 */
public void doTag() throws JspException, IOException {
// 规范属性值
if (!height.endsWith("%"))
height = height + "px";
if (!top.endsWith("px"))
top = top + "px";
if (!boxwidth.endsWith("px"))
boxwidth = boxwidth + "px";
int titlewidth = Integer.valueOf(boxwidth.replaceAll("px", ""))
.intValue() - 22;
if (tmpid == null)
tmpid = String.valueOf(System.currentTimeMillis());// 临时ID后缀,避免ID冲突
// 取得现有标签体的内容
JspFragment body = this.getJspBody();
StringWriter writer = new StringWriter();
body.invoke(writer);
// 构造带遮罩的网页对话框
StringBuffer sb = new StringBuffer();
sb.append("