通过 Tag 接口实现标签

本例通过 implements Tag 实现。

写 Tag 类

具体代码如下:

package org.iridium.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
public class HelloWorldTag implements Tag {
    private PageContext pageContext;
    private Tag parent;
    public HelloWorldTag() {
        super();
    }
    /**
     * 结束标签时的动作
     */
    @Override
    public int doEndTag() throws JspException {
        try {
            pageContext.getOut().write("Hello, world!");
        } catch (java.io.IOException e) {
            throw new JspTagException("IO error: " + e.getMessage());
        }
        return Tag.EVAL_PAGE;
    }
    /**
     * 开始标签时的动作
     */
    @Override
    public int doStartTag() throws JspException {
        return Tag.SKIP_BODY; // 不计算标签体
    }
    @Override
    public Tag getParent() {
        return this.parent;
    }
    @Override
    public void release() {
    }
    /**
     * 设置标签的页面的上下文
     */
    @Override
    public void setPageContext(PageContext pageContext) {
        this.pageContext = pageContext;
    }
    /**
     * 设置上一级标签
     */
    @Override
    public void setParent(Tag parent) {
        this.parent = parent;
    }
}

添加配置文件

创建配置文件 /WEB-INF/tlds/mytag.tld,其中内容如下:

<?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 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>
    <tag>
        <description>实现的是 Tag interface </description>
        <name>hello_inc</name>
        <tag-class>org.iridium.tags.HelloWorldTag</tag-class>
        <body-content>empty</body-content>
    </tag>
</taglib>

注:这个配置文件的後缀名也可以是别的,比如该文件也可以命名为 mytag.xml,但後续 web.xml 中配置的值和这里对应就是。

修改 web.xml

添加配置内容如下:

<web-app>
  <jsp-config>
      <taglib>
          <taglib-uri>/demotag</taglib-uri>
          <taglib-location>/WEB-INF/tlds/mytag.tld</taglib-location>
      </taglib>
  </jsp-config>
</web-app>

在 JSP 页面中使用 tag

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/demotag" prefix="hello" %>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<hello:hello_inc/>
</body>
</html>