八、SimpleTagSupport類
在JSP2.0後,為了簡化標籤開發的難度,就可以使用SimpleTagSupport進行開發;
1.開發一般標籤
注意點:
(1)需要繼承SimpleTagSupport類;
(2)實現public void doTag()throws JspException,IOException;
(3)super.getJspContext().getOut().write("...."); 進行輸出;
(4)在SimpleTagSupport中,tld中的<body-content>內容不能為JSP,如果標籤體不為空白,則只能為scriptless;
代碼:
SimpleTagSupportDemo.java
package org.tagext;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;import java.io.*;public class SimpleTagSupportDemo extends SimpleTagSupport{private String name;public String getName(){return name;}public void setName(String name){this.name = name;}public void doTag()throws JspException,IOException{super.getJspContext().getOut().write("<h3>"+name+"</h3>");}}
2.開發迭代標籤通過super.getJspBody().invoke(null);能夠執列標籤體內容;SimpleTagSupportDemo.java
package org.tagext;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;import java.io.*;import java.util.*;public class SimpleTagSupportDemo extends SimpleTagSupport{private String name;private String id;public String getName(){return name;}public void setName(String name){this.name = name;}public String getId(){return id;}public void setId(String id){this.id = id;}public void doTag()throws JspException,IOException{Object value = super.getJspContext().getAttribute(name,PageContext.PAGE_SCOPE);Iterator<String> iter = ((List<String>)value).iterator();while(iter.hasNext()){super.getJspContext().setAttribute(id,iter.next());super.getJspBody().invoke(null);}}}
綜合看來,SimpleTagSupport比起前面的TagSupport,BodyTagSupport,簡單了許多,不需要任何傳回值;九、常見問題
1.區分是否有標籤體
<xiazdong:hello name="">
</xiazdong:hello>
是屬於有標籤體的,只是標籤體為空白;
<xiazdong:hello name=""/>為標籤體為空白;