自定義標簽主要包括三個步驟:
1、編寫java類,繼承TagSupport類;
2、創建tld文件,影射標簽名和標簽的java類;
3、jsp頁面引入tld。
例子:自定義下拉框標簽
如果頁面上有下拉選擇框,通常最好的解決方法是使用數據字典,因為有可能多個頁面
使用同一個下拉框,便於後台統一維護。
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class DictionaryOptionTaget extends TagSupport {
private static final long serialVersionUID = 1L;
private String index; // 字段索引 ,頁面上通過標簽屬性傳回來的值
@SuppressWarnings("unchecked")
@Override
public int doEndTag() throws JspException {
JspWriter jspw = this.pageContext.getOut();
StringBuffer options = new StringBuffer();
/**
* 需要查詢數據庫 字段索引為SEX的option內容,這裡是寫死
*/
if ("SEX".equals(index)) {
options.append("
"); options.append("
"); options.append("
"); } try { jspw.println(options); //輸出 } catch (IOException e) { e.printStackTrace(); } return 0; } @Override public int doStartTag() throws JspException { return 0; } public String getIndex() { return index; } public void setIndex(String index) { this.index = index; } }
<code class="language-xml hljs "><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>tagSample</short-name> <uri>/hellotag</uri> <tag><!--{cke_protected}{C}%3C!%2D%2D%20%E4%BB%8E%E6%95%B0%E6%8D%AE%E5%AD%97%E5%85%B8%E6%A3%80%E5%87%BA%E4%B8%80%E4%B8%AAoption%E5%88%97%E8%A1%A8%20%2D%2D%3E--> <name>OptionDictionary</name> <tag-class> com.itmyhome.DictionaryOptionTaget </tag-class> <body-content>empty</body-content> <attribute> <name>index</name><!--{cke_protected}{C}%3C!%2D%2D%20%E5%AD%97%E6%AE%B5%E7%B4%A2%E5%BC%95%E5%90%8D%20%2D%2D%3E--> <required>true</required><!--{cke_protected}{C}%3C!%2D%2D%20%E6%98%AF%E5%90%A6%E5%BF%85%E5%A1%AB%20%2D%2D%3E--> <rtexprvalue>false</rtexprvalue><!--{cke_protected}{C}%3C!%2D%2D%20%E6%98%AF%E5%90%A6%E8%83%BD%E5%A4%9F%E4%BB%A5%24%7B%7D%E6%96%B9%E5%BC%8F%E4%BC%A0%E5%80%BC%20%2D%2D%3E--> </attribute> </tag> </taglib></code>
需要注意的是:
時候,可以使用JSP表達式
表示該自定義標簽的屬性值可以使用 ${} 方式動態傳值。
<code class="language-jsp hljs xml"><%@ taglib uri="/WEB-TAG/platForm.tld" prefix="PF"%> <select> </select></code>
頁面輸出: