自定义Tag

在JSP中使用自己定义的tag标签
步骤1:编写创建tag的java类,继承TagSupport如下:
   public class SelectTag extends TagSupport{

	private static final long serialVersionUID = 330784907215740876L;

	private String id;
	private String name;
	private String style="";
	private String spanStyle="";
	private String value="";

	public int doStartTag() throws JspException {
		canEdit = isElementEdit(name);
		JspWriter out = pageContext.getOut();
		StringBuffer buffer = new StringBuffer();
		buffer.append("<select name='").append(name).append("'")
			  .append(" style='").append(style).append("' ");
		if(null != id){
			buffer.append(" id='").append(id).append("' ");
		}
		buffer.append(">");
		try {
			out.print(buffer.toString());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Tag.EVAL_BODY_INCLUDE;
	}

	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		StringBuffer buffer = new StringBuffer();
		buffer.append("</select>");
		if(canEdit){
			buffer.append("<script type='text/javascript'>")
				  .append("selectChecked('").append(id).append("','").append(value).append("');</script>");
		} else{
			buffer.append("<span id='").append(id).append("_span' style='").append(spanStyle).append("'></span>")
				  .append("<script type='text/javascript'>")
				  .append("selectChecked('").append(id).append("','").append(value).append("',true);</script>");
		}
		try {
			out.print(buffer.toString());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Tag.EVAL_PAGE;
	}





步骤2:编写tld文件代码如下:
    <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>

	<tlibversion>1.0</tlibversion>
	<jspversion>1.1</jspversion>
	<shortname>zzz</shortname>
	<uri>http://xxxxxxx</uri>

	<tag>
		<name>select</name>
		<tagclass>com.xxxx.SelectTag</tagclass>
		<bodycontent>JSP</bodycontent>
		<attribute>
			<name>id</name>
			<required>false</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>name</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>style</name>
			<required>false</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>spanStyle</name>
			<required>false</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>value</name>
			<required>false</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
	</tag>
</taglib>



步骤3:在JSP页面上引用自定义的tld文件代码如下:
<%@ taglib uri="/WEB-INF/tld/zzz.tld" prefix="zzz"%>


附加说明:
http://oyprunner.iteye.com/blog/539494

你可能感兴趣的:(自定义)