package servlet;
import javax.servlet.jsp.tagext.*;
import java.util.Date;
import java.io.*;
import java.io.EOFException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
public class HelloTag extends BodyTagSupport {
int counts;
private int EVAL_PAGE_AGAIN;
// public void doIniBody() throws JspTagException{
// System.out.println("doIniBody");
//
// }
public void setCounts(int c){
System.out.println("setCounts");
this.counts=c;
}
// public void setBodyContent(BodyContent bodyContent){
// System.out.println("setBodyContent");
// this.bodyContent=bodyContent;
// }
public int doAfterBody() throws JspTagException{
if(counts>=1){
System.out.println(counts+"@");
System.out.println("doAfterBody---");
try{
JspWriter out=pageContext.getOut();
System.out.print(counts+"#");
out.println("doAfterBody");
out.println(counts+"@");
}catch(Exception e){
e.printStackTrace();
}
counts--;
return EVAL_BODY_AGAIN;
}else{
return SKIP_BODY;
}
}
public int doEndTag() throws JspTagException{
String dataString=new Date().toString();
System.out.println("doEndTag");
JspWriter out=pageContext.getOut();
try{
out.println("现在的时间是"+dataString);
out.print("是doEndTag");
}catch(Exception e){
throw new JspTagException("Fatal error:hello tag conld not write to JSP out");
}
return EVAL_PAGE;
}
public int doStartTag() throws JspTagException {
System.out.println("doStartTag");
JspWriter out=pageContext.getOut();
for(int i=1;i<=10;i++){
try {
out.println(i+"+#"+"Start<br>");
} catch (IOException e) {
e.printStackTrace();
}
}
return EVAL_BODY_INCLUDE;
}
public int getCounts() {
return counts;
}
}
以上是一段继承自BodyTagSupport 的一段自定义标签类,它的方法就是迭代类中的counts变量以下访问的JSP代码:
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312"%>
<%@ taglib uri="/demo" prefix="somePrefix"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>TagSupport的应用示例</title>
</head>
<body>
<%boolean b=true; %>
<%String st="hh";
pageContext.setAttribute("sss",st); %>
<c:if test="${pageScope.sss=='hh'}">
456456456456456
</c:if>
<c:set value="123123" var="sfq" scope="page"></c:set>
<c:out value="sfq"></c:out>
<somePrefix:hello counts="5">111</somePrefix:hello>
<%out.print("能不能执行"); %>
</body>
</html>
如果doStartTag()返回的是EVAL_BODY_INCLUDE-->doAfterTag()方法,如果它返回SKIP_BODY就执行doEndTag()方法.
在doAfterTag()方法中返回EVAL_BODY_AGAIN来重复执行doAfterTag()方法, 返回SKIP_BODY值则执行doEndTag()方法.
在doEndTag()方法中返回EVAL_PAGE值,则执行此标签的后的其它代码,返回SKIP_PAGE则不执行此页面的其它代码.
以上是我个人见解,如有疑问请发E-mail:sfq1984sxs@126.com联系.