jsp-自定义标签

      实现方法:

            1.创建一个java类,直接或者间接实现simpleTag,一般直接使用它的子类,simpleTagSupport,实现doTag方法;

             我写的是一个在页面自动打印时间的customTag

package com.jsp.customTag;

import java.io.IOException;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
* @author 作者 : 程呈
* @version 创建时间:2017年7月1日 下午11:11:26
* 类说明
*  用于实现simpleTagSupport
*  自定义标签one
*/
public class customTagOne extends SimpleTagSupport {
     @Override
    public void doTag() throws JspException, IOException {
             PageContext pc=(PageContext) getJspContext();
             Date date = new Date();
             pc.getOut().write(date.toLocaleString());;     
     } 
}

            2.配置一个tld文件使这个java类,使其成为一个标签。tld文件位于WEB-INF下

              

<?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.customTag</description>
    <tlib-version>1.0</tlib-version>
        <!-- ccTag:showTime -->
    <short-name>ccTag</short-name>
        <!-- 导入的URi -->
    <uri>http://www.itheima.com/customTag/ccTag</uri>
    <tag>
        <description>Outputs Hello, World</description>
        <!-- 標籤名稱 -->
        <name>showTime</name>
        <!-- 指定類路徑 -->
        <tag-class>com.jsp.customTag.customTagOne</tag-class>
        <!--empty表示 没有主体内容 -->
        <body-content>empty</body-content>
    </tag>
   </taglib>

            3.使用Taglib 指令引入。

                  

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.itheima.com/customTag/ccTag" prefix="ccTag" %>

<!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=ISO-8859-1">
<title>自定义标签customTag</title>
</head>
<body>
    <ccTag:showTime/>
</body>
</html>
怕什么真理无穷 进一寸有一寸的欢喜
原文地址:https://www.cnblogs.com/ccbk/p/7106313.html