八、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=""/>为标签体为空;