1.定義標籤類。
標籤擴充 BodyTagSupport 類。
代碼
package testtag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TagSupport;
public class LinkTag extends BodyTagSupport {
public LinkTag() {
// TODO Auto-generated constructor stub
}
private String href="";
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public int doStartTag() throws JspTagException {
return EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspTagException {
String body = this.getBodyContent().getString();
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
try {
JspWriter writer= pageContext.getOut();
String str="<a href='"+this.href+"'>"+body+"</a>";
pageContext.getOut().print(str);
}
catch (IOException e) {
throw new JspTagException(e.getMessage());
}
return SKIP_BODY;
}
}
2.定義標籤檔案 MyTagLib.tld。
代碼
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<tag>
<name>linktag</name>
<tag-class>testtag.LinkTag</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>href</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3.在web.xml中添加引用。
<jsp-config>
<taglib>
<taglib-uri>MyTagLib</taglib-uri>
<taglib-location>/WEB-INF/MyTagLib.tld</taglib-location>
</taglib>
</jsp-config>
4.在頁面中調用自訂標籤。
<%@taglib uri="MyTagLib" prefix="mytag"%>
<mytag:linktag href="http://www.baidu.com">測試標籤</mytag:linktag>