posts - 431,  comments - 344,  trackbacks - 0

开发和使用自定义标签程序有三个步骤:
1.开发标签实现类
2.编写标签描述,这个描述通常是以.tld结尾的文件
3.在web.xml中指定标签库的引用

开发实现:

package com.rain.tag;

import Java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class HelloTag implements Tag {

 private PageContext pageContext;
 private Tag parent;
 
 public HelloTag(){
  super();
 }
 public int doEndTag() throws JspException {
  // TODO Auto-generated method stub
  try{
   pageContext.getOut().write("Hello World! 你好");
  }catch(IOException e){
   throw new JspTagException("IO Error:"+e.getMessage());
  }
  return EVAL_PAGE;
 }

 public int doStartTag() throws JspException {
  // TODO Auto-generated method stub
  return SKIP_BODY;  //返回SKIP_BODY,表示不计算标签体
 }

 public Tag getParent() {
  // TODO Auto-generated method stub
  return this.parent;
 }

 public void release() {
  // TODO Auto-generated method stub
 }

 public void setPageContext(PageContext arg0) {
  // TODO Auto-generated method stub
  this.pageContext=arg0;
 }

 public void setParent(Tag arg0) {
  // TODO Auto-generated method stub
  this.parent=arg0;
 }

}

编写标签库描述

<?xml version="1.0" encoding="UTF-8" ?>
<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 web-jsptaglibrary_2_0.xsd"
        version="2.0">
        <description>A tag library exercising SimpleTag handlers.</description>
        <tlib-version>1.0</tlib-version>
       
        <short-name>examples</short-name>
        <uri>/demotag</uri>
        <description>JSP应用开发</description>
       
        <tag>
          <description>Outputs Hello,World</description>
          <name>hello_int</name>
          <tag-class>com.rain.tag.HelloTag</tag-class>
          <body-content>empty</body-content>
        </tag>
</taglib>

使用自定义标签

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
 <taglib>
   <taglib-uri>/demotag</taglib-uri>
   <taglib-location>/WEB-INF/mytag.tld</taglib-location>
 </taglib>
</web-app>


<%@ page language="Java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="/demotag" prefix="hello" %>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<p>以下的内容是从Taglib中显示的:</p>
<p><i><hello:hello_int/></i></p>
</body>
</html>

本实例是实现Tag接口,但为了在开发中方便简单,一般直接继承TagSupport类,只覆盖doStartTag和doEndTag两个方法就可以。TagSupport是Tag的子类。

posted on 2007-01-22 11:53 周锐 阅读(1396) 评论(0)  编辑  收藏 所属分类: Jsp

只有注册用户登录后才能发表评论。


网站导航: