自定义标签:
1.作用:
替换JSP页面中的java脚本(<%%>)。(官方推荐:JSP2.0开始)
2.开发步骤:
编写一个实现Tag接口的Java类(标签处理器类)
编写标签库描述符(tld)文件,在tld文件中把标签处理器类进行描述:
Interface SimpleTag
void |
doTag() Called by the container to invoke this tag. 当容器在页面上碰到该标签时,自定义标签时自动调用doTag()方法, |
JspTag |
getParent() Returns the parent of this tag, for collaboration purposes. |
void |
setJspBody(JspFragment jspBody) 设置标签的主体Provides the body of this tag as a JspFragment object, able to be invoked zero or more times by the tag handler. |
void |
setJspContext(JspContext pc) Called by the container to provide this tag handler with the JspContext for this invocation. |
void |
setParent(JspTag parent) Sets the parent of this tag, for collaboration purposes. |
ss Class SimpleTagSupport
void |
doTag() Default processing of the tag does nothing. |
static JspTag |
findAncestorWithClass(JspTag from,Class<?> klass) Find the instance of a given class type that is closest to a given instance. |
protected JspFragment |
getJspBody() Returns the body passed in by the container via setJspBody. |
protected JspContext |
getJspContext() Returns the page context passed in by the container via setJspContext. |
JspTag |
getParent() Returns the parent of this tag, for collaboration purposes. |
void |
setJspBody(JspFragment jspBody) Stores the provided JspFragment. |
void |
setJspContext(JspContext pc) Stores the provided JSP context in the private jspContext field. |
void |
setParent(JspTag parent) Sets the parent of this tag, for collaboration purposes. |
a、编写一个类,直接或间接实现javax.servlet.jsp.tagext.SimpleTag,一般选择继承javax.servlet.jsp.tagext.SimpleTagSupport,覆盖掉doTag方法
package com.heima.jstl;
import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
//演示输出当前时间
public class ShowTime extends SimpleTagSupport{
//执行doTag之前,容器就已经调用了void setJspContext(JspContext pc),传入了PageCont