j2ee 基础知识点笔记(五) - 15841333625/Java GitHub Wiki

自定义标签

***<%@ taglib uri="/WEB-INF/tlds/time.tld" prefix="t" %> // 加前缀,区分两个不同的time标记
<%@ taglib uri="/WEB-INF/tlds/b.tld" prefix="ab" %>      // uri也可能是http:\\...

// 调用 doTag() 
<t:time format="hh:mm"> // 向处理器传数据,require=false,不是必须的 // 调用doStartTag()
</t:time>                                                          // 调用doEndTag()
<ab:time></ab:time>
import java.util.*;
import java.servlet.jsp.tagext.*;
import java.servlet.jsp.*;
import java.servlet.http.*;

public class Tag extends SimpleTagSupport/TagSupport {
  private String format = "yyyy-mm-dd";
  public void setFormat(String format) {  // jsp 传入属性值
    this.format = format;
  }
  // SimpleTagSupport
  public void doTag() throws JspException, IOExcwption{
    String str = SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
    getJspContext().getOut().print (str);

    PageContext pageContext = (PageContext) getJspContext();
    PageContext.setAttribute("a", "lll"); // 其他页面通过${a}获取这个属性

    HttpSession session = pageContext.getSession();
    String username = (String) session.getAttribute("username");
  }

  // TagSupport
  public int doStartTag() throws JspException {
    try {
      pageContext.getOut().print();
    } catch(Exception e) {
      throw new JspException(e);
    }
    return EVAL_BODY_INCLUDE;
  }
}
public class MyTagExtraInfo extends TagExtraInfo {
  public VariableInfo[] getVariableInfo(TagData td) {
    return new VariableInfo[] {
      new VariableInfo("a", "java.lang.String", true, VariableInfo.AT_END);
    }
  } 
}
time.tld 文件
/WEB-INF/tlds
         time.tld

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE taglib>
<taglib>
  <tlib-version>1.1</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>mytags</short-name>
  <uri>http://java.sun.com/jsp/jstl/core</uri>

  <tag>
    <name>time</name>
    <tag-class>TimeTag</tag-class>
    <tei-class>MyTagExtraInfo</tei-class>***   
    <body-content>JSP</body-content>
    <attribute>
      <name>format</name>
      <type>java.lang.String</type>
      <required>false</required>      <!-- 是不是必须的 -->
      <rtexprvalue>true</rtexprvalue> <!-- 可以提供动态值 -->
    </attribute>
  </tag>
</taglib>

Tag

IterationTag 迭代标签

EVAL_BODY_AGAIN 重新解析体内容  
doAfterBody() 返回值 SKIP_BODY; EVAL_BODY_AGAIN;  
// 迭代5次
<a:hello count="5">
</a:hello>
// 迭代标记,jsp内容迭代
public void setCount(int count) {
 this.count = count;
}
public int doAfterBody() {
 count--;
 if(count==0) { return SKIP_BODY; }
 else { return EVAL_BODY_AGAIN; }
}

TAG FILE

自定义标记处理器 在jsp中实现
time.jsp
time.tag // jsp 语法 文件名即为标记名称
保存到

/WEB-INF/tags/
     classes
     lib
<%@ taglib tagdir="/WEB-INF/tags" prefix="a" %>
<%@ attribute name="" type="" required="true" rtexpralue="true" %>  // 传属性
⚠️ **GitHub.com Fallback** ⚠️