1. 程式人生 > >javaweb帶屬性的自定義標籤

javaweb帶屬性的自定義標籤

帶屬性的自定義標籤:

1.先在標籤處理器中定義setter方法,建議把所有的屬性型別都設定為String型別。

package com.javaweb.tag;

import java.io.IOException;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag;

public class HelloSimpleTag implements SimpleTag {
	private String value;
	private String count;
	
	public void setCount(String count) {
		this.count = count;
	}

	public void setValue(String value) {
		this.value = value;
	}

	//標籤體的邏輯實際應該編寫到此方法中
	@Override
	public void doTag() throws JspException, IOException {
		JspWriter out=pageContext.getOut();
		int c=0;
		c=Integer.parseInt(count);
		for(int i=0;i<c;i++){
			out.print((i+1)+":"+value);
			out.print("<br>");
		}
	}

	@Override
	public JspTag getParent() {
		System.out.println("getParent");
		return null;
	}

	@Override
	public void setJspBody(JspFragment arg0) {
		System.out.println("setJspBody");
	}
    private PageContext pageContext;
    //JSP引擎呼叫,把代表jsp頁面的PageContext物件傳入
	@Override
	public void setJspContext(JspContext arg0) {
		System.out.println(arg0 instanceof PageContext);
		this.pageContext=(PageContext)arg0;
	}

	@Override
	public void setParent(JspTag arg0) {
		System.out.println("setParent");
	}

}

2.在tld檔案中描述屬性

<attribute>
    <!-- 屬性名,需和標籤處理器類的setter方法定義的屬性相同 -->
    <name>value</name>
    <!-- 該屬性是否被必須 -->
    <required>true</required>
    <!-- rtexprvalue:runtime expression value  當前屬性是否可以接受執行時表示式的動態值 -->
    <rtexprvalue>true</rtexprvalue>
 </attribute>
  
  <attribute>
    <name>count</name>
    <required>true</required>
    <rtexprvalue>true</rtexprvalue>
 </attribute>

 3.在jsp頁面中使用屬性

屬性名同tld檔案中定義的名字。

<koala:hello value="koala" count="8"/>