JSP的自定义标签

自定义标签
标签库由三个部分组成:标签处理程序类(提供功能)、标签库描述符(TLD文件,描述标签并将标签与处理程序匹配)、标签库指示(放在JSP文件,通过它使用标签)
相应的,JSP提供三种接口可以利用:Tag,IterationTag和BodyTag,也可以利用TagSupport类或者BodyTagSupport类扩展

1 基本的使用方法
例子:显示时间
传统的方式是利用JavaBean分离数据
Time.java文件为:
package javabeans;

import java.text.SimpleDateFormat;

public class Time {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日HH点mm分ss秒");
        String time = sdf.format(new java.util.Date());

        public String getTime() {
                return time;
        }
}

index.jsp文件:
<%@page contentType="text/html;charset=GBK"%>
<html>
<head>
</head>
<body>
<jsp:useBean id="time" class="javabeans.Time" />
<jsp:getProperty name="time" property="time" />
</body>
</html>

但是网页的格式化信息难以有效的结合进行JavaBean中
package javabeans;

import java.text.SimpleDateFormat;

public class Time {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日HH点mm分ss秒");
        String time = sdf.format(new java.util.Date());

        public String getTime() {
                StringBuffer result = new StringBuffer();
                result.append("<span style = 'background-color: black;color: cyan;'>");
                result.append(time);
                result.append("</span>");
                return result.toString();
        }
}

事实上,JavaBean只负责数据,不仅可以给Web程序提供数据,还可以给其他诸如窗体程序提供数据,所以也不应该嵌入HTML的格式代码

利用标签可以完成该项任务
TimeTag文件为:
package taglib;

import javabeans.Time;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TimeTag extends TagSupport {
        Time time = new Time();

        public int doEndTag() throws JspException {
                try {
                        pageContext.getOut().print(
                                        "<span style = 'background-color: black;color: cyan;'>");
                        pageContext.getOut().print(time.getTime());
                        pageContext.getOut().print("</span>");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

注意:pageContext属性用于代表Web应用中的PageContext对象,它里面还有setAttribute方法和getAttribute方法可以保存和访问Web应用中的共享数据,两个方法都需要指定scope参数来说明属性存在的范围。这个属性不能在TagSupport构造函数中使用,因为此时还没初始化pageContext属性。除此外,还有一个parent属性代表嵌套了当前标签的上层标签的处理类,但是必须通过getParent方法获得引用

time.tld文件为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri></uri>
        <info></info>
        <tag>
                <name>time</name>
                <tagclass>taglib.TimeTag</tagclass>
        </tag>
</taglib>
放入Web应用程序根目录

index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="time.tld"%>

<html>
<head>
</head>
<body>
<mytag:time />
</body>
</html>

注意:
1)如果time.tld文件不在当前目录,如在WEB-INF下,则可以换成:
<%@ taglib prefix="mytag" uri="../WEB-INF/time.tld" %>
2)这里直接使用实际uri,也可以使用web.xml进行路径转换
        <jsp-config>
                <taglib>
                        <taglib-uri>time</taglib-uri>
                        <taglib-location>/time.tld</taglib-location>
                </taglib>
        </jsp-config>
3)一般JSP容器先把uri作为路径进行查找,如不可行,则检查web.xml文件进行查找

此时的网页为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="time"%>

<html>
<head>
</head>
<body>
<mytag:time />
</body>
</html>

注意:可能由于Tomcat服务器缓存的原因,导致不能及时刷新,解决方法有:
1)让JSP不缓存方法网页头部加上
<%
response.setHeader("Pragma","No-cache");//HTTP 1.1
response.setHeader("Cache-Control","no-cache");//HTTP 1.0
response.setHeader("Expires","0");//防止被proxy
%>
2)修改conf/server.xml 文件Context path 中间加上 reloadable="true"
例如:<Context path="" docBase="E:/MYJSP/" debug="0" reloadable="true" />

2 标签类的方法
在标签处理程序类中,重要的是实现doStartTag()和doEndTag(),程序读到<mytag:time>开始部分,调用doStartTag(),程序读到</mytag:time>结束部分,调用doEndTag()
遇到开始标签,调用doStartTag(),返回值为EVAL_BODY_INCLUDE或是SKIP_BODY,前者将引起标签体的计算,后者不计算
遇到结束标签,调用doEndTag(),如是空标签也会执行,返回值为EVAL_PAGE和SKIP_PAGE,前者继续执行标签后的JSP代码,后者结束JSP网页的生成,直接将现有内容发向客户端

修改TimeTag.java文件:
package taglib;

import javabeans.Time;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TimeTag extends TagSupport {
        Time time = new Time();

        public int doStartTag() throws JspException {
                try {
                        pageContext.getOut().print("[");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }

        public int doEndTag() throws JspException {
                try {
                        pageContext.getOut().print(
                                        "<span style = 'background-color: black;color: cyan;'>");
                        pageContext.getOut().print(time.getTime());
                        pageContext.getOut().print("</span>");
                        pageContext.getOut().print("]");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="time.tld"%>

<html>
<head>
</head>
<body>
<mytag:time>Some text</mytag:time>
</body>
</html>

再次修改TimeTag.java文件:
package taglib;

import javabeans.Time;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TimeTag extends TagSupport {
        Time time = new Time();

        public int doStartTag() throws JspException {
                try {
                        pageContext.getOut().print("[");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return SKIP_BODY;// 注意
        }

        public int doEndTag() throws JspException {
                try {
                        pageContext.getOut().print(
                                        "<span style = 'background-color: black;color: cyan;'>");
                        pageContext.getOut().print(time.getTime());
                        pageContext.getOut().print("</span>");
                        pageContext.getOut().print("]");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

此时将忽略标签体的内容

再次修改TimeTag.java文件:
package taglib;

import javabeans.Time;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TimeTag extends TagSupport {
        Time time = new Time();

        public int doStartTag() throws JspException {
                try {
                        pageContext.getOut().print("[");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }

        public int doEndTag() throws JspException {
                try {
                        pageContext.getOut().print(
                                        "<span style = 'background-color: black;color: cyan;'>");
                        pageContext.getOut().print(time.getTime());
                        pageContext.getOut().print("</span>");
                        pageContext.getOut().print("]");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return SKIP_PAGE;// 注意
        }
}

index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="time.tld"%>

<html>
<head>
</head>
<body>
<mytag:time>Some text</mytag:time>
<%=new java.util.Date()%>
</body>
</html>

此时将忽略网页中后续代码的计算

总结:
EVAL_BODY_INCLUDE:把Body读入存在的输出流中,doStartTag()函数可用
EVAL_PAGE:继续处理页面,doEndTag()函数可用
SKIP_BODY:忽略对Body的处理,doStartTag()和doAfterBody()函数可用
SKIP_PAGE:忽略对余下页面的处理,doEndTag()函数可用
EVAL_BODY_TAG:已经废止,由EVAL_BODY_BUFFERED取代
EVAL_BODY_BUFFERED:申请缓冲区,由setBodyContent()函数得到的BodyContent对象来处理tag的body,如果类实现了BodyTag,那么doStartTag()可用,否则非法

3 标签的属性
3、1 利用页面变量传递属性(也被称为代码段变量,使用标签处理程序创建的变量被称为代码段变量)
修改标签文件为:
package taglib;

import javabeans.Time;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TimeTag extends TagSupport {
        Time time = new Time();

        public int doEndTag() throws JspException {
                try {
                        String fgColor = pageContext.getRequest().getParameter("fgColor");
                        String bgColor = pageContext.getRequest().getParameter("bgColor");
                        if (fgColor == null)
                                fgColor = "black";
                        if (bgColor == null)
                                bgColor = "white";
                        pageContext.getOut().print(
                                        "<span style = 'background-color: " + bgColor + ";color: "
                                                        + fgColor + ";'>");
                        pageContext.getOut().print(time.getTime());
                        pageContext.getOut().print("</span>");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="time.tld"%>
<html>
<head>
</head>
<body>
<mytag:time />
<form action="index.jsp" method="Post">前景色:<select name='fgColor'>
        <option value="red" style="background-color: red">red</option>
        <option value="blue" style="background-color: blue">blue</option>
        <option value="cyan" style="background-color: cyan" selected>cyan</option>
        <option value="black" style="background-color: black; color: white">black</option>
</select> <br>
背景色: <select name='bgColor'>
        <option value="gray" style="background-color: gray; color: white">gray</option>
        <option value="yellow" style="background-color: yellow">yellow</option>
        <option value="black" style="background-color: black" selected>black</option>
        <option value="white" style="background-color: white">white</option>
</select> <br>
<input type="submit" name="submit" value="确认"></form>
</body>
</html>

运行观察效果
http://localhost:8088/myweb/index.jsp?fgColor=yellow&bgColor=blue

3、2 利用标签属性
修改标签为:
package taglib;

import javabeans.Time;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TimeTag extends TagSupport {
        Time time = new Time();
        String fgColor = "black";
        String bgColor = "white";

        public void setTime(Time time) {
                this.time = time;
        }

        public void setFgColor(String fgColor) {
                this.fgColor = fgColor;
        }

        public void setBgColor(String bgColor) {
                this.bgColor = bgColor;
        }

        public int doEndTag() throws JspException {
                try {
                        pageContext.getOut().print(
                                        "<span style = 'background-color: " + bgColor + ";color: "
                                                        + fgColor + ";'>");
                        pageContext.getOut().print(time.getTime());
                        pageContext.getOut().print("</span>");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

相应的time.tld文件为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri></uri>
        <info></info>
        <tag>
                <name>time</name>
                <tagclass>taglib.TimeTag</tagclass>
                <attribute>
                        <name>fgColor</name>
                        <rtexprvalue>true</rtexprvalue>
                </attribute>
                <attribute>
                        <name>bgColor</name>
                        <rtexprvalue>true</rtexprvalue>
                </attribute>
                </tag>
</taglib>

注意:rtexprvalue的全称是 Run-time Expression Value,表示是否可以在运行时动态生成属性值,默认为false

index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="time.tld"%>
<html>
<head>
</head>
<body>
<mytag:time fgColor="red" bgColor="yellow" />
</body>
</html>

4 IterationTag接口的使用
和Tag相似,能够重复计算标签组成的代码体。IterationTag通过扩展Tag实现doAfterBody来进行循环,它只有在doStartTag返回值为EVAL_BODY_INCLUDE后才调用,而且doAfterBody返回值为EVAL_BODY_AGAIN才进行下一轮循环,直至SKIP_BODY或者EVAL_BODY_INCLUDE才停止

标签类仍然可以使用TagSupport类扩展得到,如:
package taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class IterationTag extends TagSupport {
        private int count = 0;
        private String[] strings = null;

        public int doStartTag() {
                strings = (String[]) pageContext.getAttribute("strings");
                return EVAL_BODY_INCLUDE;
        }

        public int doAfterBody() throws JspException {
                try {
                        pageContext.getOut().print(strings[count].toString() + "<br>");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                count++;
                if (count >= strings.length)
                        return SKIP_BODY;
                return EVAL_BODY_AGAIN;
        }
}

mytags.tld文件为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri></uri>
        <info></info>
        <tag>
                <name>iteration</name>
                <tagclass>taglib.IterationTag</tagclass>
        </tag>
</taglib>

index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="iterator" uri="mytags.tld"%>
<html>
<head>
</head>
<body>
<h1>
<%
        String[] str = new String[] { "Apple", "Banana", "Orange" };
        pageContext.setAttribute("strings", str);
%> <iterator:iteration>The string is:</iterator:iteration></h1>
</body>
</html>

5 BodyTag接口
是三个标签接口中最大,最通用的接口,扩展了IterationTag接口,允许标签改变网页内容

6 通过TLD文件使用代码段变量
使用标签处理程序创建的对象称为代码段变量,与<jsp:useBean>和<scriptlet>创建的效果一样,但是更加简单方便,如标签创建的对象可以被合作标签使用和scriptlet使用
具体的使用方式是通过网页或者会话的参数属性来传递

1 一般的方法
标签为:
package taglib;

import javax.servlet.jsp.tagext.TagSupport;

public class DataSeedTag extends TagSupport {
        public int doStartTag() {
                String[] str = new String[] { "Apple", "Banana", "Orange" };
                pageContext.setAttribute("strings", str);
                return EVAL_PAGE;
        }
}

mytags.tld文件为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri></uri>
        <info></info>
        <tag>
                <name>array</name>
                <tagclass>taglib.DataSeedTag</tagclass>
        </tag>
</taglib>

index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="mytags.tld"%>
<html>
<head>
</head>
<body>
<h1><mytag:array /> <%
        String[] strings = (String[]) pageContext.getAttribute("strings");
 %>There are <%=strings.length%> variables!
<p>
<%
        for (int i = 0; i < strings.length; i++)
                out.println("The value is " + strings[i] + "<P>");
%>

</h1>
</body>
</html>

2 使用代码段变量
修改mytags.tld文件为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri></uri>
        <info></info>
        <tag>
                <name>array</name>
                <tagclass>taglib.DataSeedTag</tagclass>
                <variable>
                        <name-given>strings</name-given>
                        <variable-class>java.lang.String [] </variable-class>
                        <declare>true</declare>
                        <scope>AT_END</scope>
                </variable>
        </tag>
</taglib>

注意:tld文件中使用了<variable>子元素来定义代码段变量,使得下面的JSP文件的变量声明可以省略。文件中的各个元素说明如下:
<name-given>名称
<variable-class>类型
<declare>判断代码段变量是新定义的(true)还是已经存在的(false,前面的网页中已经声明过)
<scope>定义代码段的使用范围,AT_BEGIN表示在起始标签处创建代码段变量,AT_END表示在结束标签处创建代码段变量,NESTED表示代码段变量只在自定义标签的起始标签和结束标签之间有效

修改index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="mytags.tld"%>
<html>
<head>
</head>
<body>
<h1><mytag:array />There are <%=strings.length%> variables!
<p>
<%
        for (int i = 0; i < strings.length; i++)
                out.println("The value is " + strings[i] + "<P>");
%>
</h1>
</body>
</html>

注意:此时无需获取strings变量,可以直接使用

再次修改标签文件为:
package taglib;

import javax.servlet.jsp.tagext.TagSupport;

public class DataSeedTag extends TagSupport {
        public int doStartTag() {
                String[] str = new String[] { "Apple", "Banana", "Orange" };
                pageContext.setAttribute("strings", str);
                pageContext.setAttribute("length",new Integer(str.length));
                return EVAL_PAGE;
        }
}

修改mytags.tld文件,增加为:
                <variable>
                        <name-given>length</name-given>
                        <variable-class>java.lang.Integer</variable-class>
                        <declare>true</declare>
                        <scope>NESTED</scope>
                </variable>


修改index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="mytags.tld"%>
<html>
<head>
</head>
<body>
<h1><%--Total:<%=length%><P>--%> <mytag:array>The string length is <%=length%></mytag:array>
</h1>
</body>
</html>

注意:
1)如果将注释去除则会异常
2)如果使用一般的注释也会异常,如<!--和-->,因为<%--和--%>注释编译后在servlet中看不见
此时观察JSP生成的Servlet源码会看到内容,如:
      out.write("<!--Total:");
      out.print(length);
      out.write("<P>-->/r/n");

3 例子
1)一个结合循环标签和代码段变量的例子
增加循环标签为:
package taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class IterationTag extends TagSupport {
        private int index = 0;
        private String[] strings = null;

        public int doStartTag() {
                strings = (String[]) pageContext.getAttribute("strings");
                pageContext.setAttribute("current", strings[index]);
                pageContext.setAttribute("index", new Integer(index));
                return EVAL_PAGE;
        }

        public int doAfterBody() throws JspException {
                index++;
                if (index >= strings.length)
                        return SKIP_BODY;
                pageContext.setAttribute("current", strings[index]);
                pageContext.setAttribute("index", new Integer(index));
                return EVAL_BODY_AGAIN;
        }
}

修改mytags.tld文件为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri></uri>
        <info></info>
        <tag>
                <name>iteration</name>
                <tag-class>taglib.IterationTag</tag-class>
                <variable>
                        <name-given>current</name-given>
                        <variable-class>java.lang.String</variable-class>
                        <declare>true</declare>
                        <scope>NESTED</scope>
                </variable>
                <variable>
                        <name-given>index</name-given>
                        <variable-class>java.lang.Integer</variable-class>
                        <declare>true</declare>
                        <scope>NESTED</scope>
                </variable>
        </tag>
        <tag>
                <name>array</name>
                <tag-class>taglib.DataSeedTag</tag-class>
                <variable>
                        <name-given>strings</name-given>
                        <variable-class>java.lang.String [] </variable-class>
                        <declare>true</declare>
                        <scope>AT_END</scope>
                </variable>
        </tag>
</taglib>

修改index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="mytags.tld"%>

<html>
<head>
</head>
<body>
<h1><mytag:array></mytag:array> <mytag:iteration>
The string is: <%=current%> at <%=index%><p>
</mytag:iteration></h1>
</body>
</html>

2)完全使用标签的改进例子
增加标签IndexTag为:
package taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class IndexTag extends TagSupport {
        public int doEndTag() throws JspException {
                int index = ((Integer) (pageContext.getAttribute("index"))).intValue();
                try {
                        pageContext.getOut().print(index);
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

增加标签TextTag为:
package taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TextTag extends TagSupport {
        public int doEndTag() throws JspException {
                String current = (String) (pageContext.getAttribute("current"));
                try {
                        pageContext.getOut().print(current);
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

修改mytags.tld文件为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri></uri>
        <info></info>
        <tag>
                <name>iteration</name>
                <tag-class>taglib.IterationTag</tag-class>
        </tag>
        <tag>
                <name>array</name>
                <tag-class>taglib.DataSeedTag</tag-class>
        </tag>
        <tag>
                <name>array.index</name>
                <tag-class>taglib.IndexTag</tag-class>
        </tag>
        <tag>
                <name>array.text</name>
                <tag-class>taglib.TextTag</tag-class>
        </tag>
</taglib>

修改index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytag" uri="mytags.tld"%>

<html>
<head>
</head>
<body>
<h1><mytag:array /> <mytag:iteration>
The string is:<mytag:array.text /> at <mytag:array.index />
        <p>
</mytag:iteration></h1>
</body>
</html>

7 标签库的JAR文件
具体做法:
1)生成标签类
package taglib;

import java.text.SimpleDateFormat;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TimeTag extends TagSupport {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日HH点mm分ss秒");
        String time = sdf.format(new java.util.Date());

        public int doEndTag() throws JspException {
                try {
                        pageContext.getOut().print(
                                        "<span style = 'background-color: black;color: cyan;'>");
                        pageContext.getOut().print(time);
                        pageContext.getOut().print("</span>");
                } catch (Exception e) {
                        throw new JspException(e.toString());
                }
                return EVAL_PAGE;
        }
}

2)生成标签的TLD文件(如mytags.tld),确保里面有<uri>http://www.njmars.net</uri>节点,并将此文件放入META-INF目录下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
        <tlibversion>1.0</tlibversion>
        <jspversion>1.2</jspversion>
        <shortname></shortname>
        <uri>http://www.njmars.net</uri>
        <info></info>
        <tag>
                <name>time</name>
                <tag-class>taglib.TimeTag</tag-class>
        </tag>
</taglib>

3)将完整的标签类包文件和tld文件复制到其他工作目录下,命令提示符下使用指令:
jar cvf time.jar taglib/*.class META-INF/mytags.tld

4)新建其他Web应用程序,将jar文件放入当前应用程序的WEB-INF/lib文件夹下
相应的index.jsp网页为:
<%@page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="mytags" uri="http://www.njmars.net"%>
<html>
<head>
</head>
<body>
<h1><mytags:time/></h1>
</body>
</html>

注意:<%@ taglib prefix="mytags" uri="http://www.njmars.net"%>中的uri既非真实路径,也非web.xml中的信息,而是tld文件中的<uri>信息

8 JSP2.0提供的TAG标签定义方法
也被称为Simple Tag,它继承的类为SimpleTagSupport
1)新建WEB-INF/tags目录,新建hello.tag文件,内容为:
<table border="1">
   <tr><td>Hello! World!</td></tr>
</table>

2)新建index.jsp文件为:
<%@page contentType="text/html;charset=GBK"%>
<%@taglib prefix="demo" tagdir="/WEB-INF/tags"%>
<html>
<body>
<demo:hello />
</body>
</html>

注意:
在Tag File中也可以使用out、config、request、response、session、application、jspContext等对象,如:
<table border="1">
<tr>
<td>
<%
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                        "yyyy年M月d日HH点mm分ss秒");
        String time = new String(sdf.format(new java.util.Date()).getBytes(
                        "ISO-8859-1"), "GBK");
        out.print("<span style = 'background-color: black;color: cyan;'>");
        out.print(time);
        out.print("</span>");
%></td>
</tr>
</table>

此时可能要修改Eclipse的JSP Tag Definition默认字符集

展开阅读全文
©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值