第一步、建立一個jsp標籤庫:在WEB-INF\tld\目錄下面創建 一個後綴爲 .tld的文件,Test.tld文件內容格式如下:
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<tag>
<name>write</name>
<tagclass>com.tag.PageTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>url</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>addIndex</name>
<required>false</required>
<type>Boolean</type>
</attribute>
</tag>
</taglib>
創建一個標籤對應的類文件
public class PageTag extends TagSupport {
private String url;
private boolean addIndex = true;
public void setUrl(String url) {
this.url = url;
}
public void setAddIndex(boolean addIndex) {
this.addIndex = addIndex;
}
public int doStartTag() throws JspException {
try {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
HttpSession session = request.getSession();
JspWriter out = pageContext.getOut();
out.print("輸出內容信息");
} catch (java.io.IOException e) {
throw new JspTagException(e.getMessage());
} catch (Exception e) {
throw new JspTagException(e.getMessage());
}
return SKIP_BODY;
}
}
第二步、在web.xml配置文件中進行如下配置:
<!-- jsp自定義標籤 -->
<jsp-config>
<taglib>
<taglib-uri>Page-Tags</taglib-uri>
<taglib-location>/WEB-INF/tld/Test.tld</taglib-location>
</taglib>
</jsp-config>
第三步、jsp頁面上的引用:
引用標籤庫:
<%@ taglib uri="Page-Tags" prefix="p"%>
使用標籤:
<p:write url="test" />