---
title: "[jsp自定义标签1] jsp自定义标签的处理过程"
author: "huangfoxAgain"
date: "2011-03-14T20:31:34Z"
tags: ["F#", "JSP", "Servlet", "Web", "XML"]
categories: ["编程语言"]
slug: "jsp-1-jsp"
draft: false
lastmod: "2011-03-14T20:43:52Z"
id: 962116
url: "https://huangfoxagain.iteye.com/blog/962116"
---

jsp自定义标签可以封装一定的功能，在某种层面上实现数据和展示的分离。 jsp自定义标签的主要工作包括： 1.创建标签的处理类(Tag Handler Class) 2.创建标签库描述文件(Tag Library Descriptor File) 3.在web.xml文件中配置元素 4.在JSP文件中引人标签库 下面给出一个简单的例子： 1.tag handler class \[code="java"]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 { @Override public int doEndTag() throws JspException { JspWriter out = pageContext.getOut(); try { out.print("do End Tag "); } catch (IOException e) { e.printStackTrace(); } return super.doEndTag(); } @Override public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); try { out.print("hello！"); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } }\[/code] 2.tag library descriptor file (tld) \[code="java"] 1.0 myTagLib /myTag helloTag com.fox.mytag.HelloMyTag empty \[/code] 3.web.xml配置tag \[code="java"] /myTag /WEB-INF/tag/mytag.tld \[/code] 4.自定义标签的使用 &lt;%@ taglib prefix="f" uri="/myTag" %&gt; -------------------------------------- 自定义标签的处理流程： \[color=red]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方法完成相应的处理\[/color]