[jsp自定义标签1] jsp自定义标签的处理过程
jsp自定义标签可以封装一定的功能,在某种层面上实现数据和展示的分离。
jsp自定义标签的主要工作包括:
1.创建标签的处理类(Tag Handler Class)
2.创建标签库描述文件(Tag Library Descriptor File)
3.在web.xml文件中配置元素
4.在JSP文件中引人标签库
下面给出一个简单的例子:
1.tag handler class
package com.fox.mytag;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.TagSupport;public class HelloMyTag extends TagSupport {@Overridepublic int doEndTag() throws JspException {JspWriter out = pageContext.getOut();try {out.print("do End Tag ");} catch (IOException e) {e.printStackTrace();}return super.doEndTag();}@Overridepublic int doStartTag() throws JspException {JspWriter out = pageContext.getOut();try {out.print("<font color=\"red\">hello!</font>");} catch (IOException e) {e.printStackTrace();}return super.doStartTag();}}2.tag library descriptor file (tld)
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <short-name>myTagLib</short-name> <uri>/myTag</uri> <tag> <name>helloTag</name> <tag-class>com.fox.mytag.HelloMyTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
3.web.xml配置tag
<jsp-config> <taglib> <taglib-uri>/myTag</taglib-uri> <taglib-location>/WEB-INF/tag/mytag.tld</taglib-location> </taglib> </jsp-config>
4.自定义标签的使用
<%@ taglib prefix="f" uri="/myTag" %>
<f:helloTag/>
--------------------------------------
自定义标签的处理流程:
1.在JSP中引入标签库:
2.在JSP中使用标签库标签:
3.Web容器根据第二个步骤中的prefix,获得第一个步骤中声明的taglib的uri属性值
4.Web容器根据uri属性在web.xml找到对应的元素
5.从元素中获得对应的元素的值
6.Web容器根据元素的值从WEB-INF/目录下找到对应的.tld文件
7.从.tld文件中找到与tagname对应的元素
8.凑元素中获得对应的元素的值
9.Web容器根据元素的值创建相应的tag handle class的实例
10. Web容器调用这个实例的doStartTag/doEndTag方法完成相应的处理