JavaWeb--自定义简单标签1

首先导入两个包

在jsp中写:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 下面这样即可遍历:

<c:forEach items="${requestScope.customers}" var="customer">
    ${customer.id}, ${customer.name}, ${customer.age}<br>
</c:forEach>

自定义标签的开发与应用步骤
  1.编写完成标签功能的 Java 类(标签处理器)
  2.编写标签库描述(tld)文件,在tld文件中对自定义中进行描述
  3.在 JSP 页面中导入和使用自定义标签

1.编写完成标签功能的 Java 类(标签处理器)

package tagTest;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag;
import java.io.IOException;

public class HelloSimpleTag implements SimpleTag {


    @Override
    public void doTag() throws JspException, IOException {
        System.out.println("doTag");
    }

    @Override
    public void setParent(JspTag jspTag) {
        System.out.println("setParent");
    }

    @Override
    public JspTag getParent() {
        System.out.println("getParent");
        return null;
    }

    @Override
    public void setJspContext(JspContext jspContext) {
        System.out.println("setJspContext");
    }

    @Override
    public void setJspBody(JspFragment jspFragment) {
        System.out.println("setJspBody");
    }
}

 2.编写标签库描述(tld)文件,在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>MyTag 1.0 core library</description>
    <display-name>MyTag core</display-name>
    <tlib-version>1.0</tlib-version>

    <!--建议在JSP页面使用的标签前缀-->
    <short-name>skye</short-name>
    <!--作为tld文件的id,用来唯一标识当前的tld文件,多个tld文件的uri不能重复,通过JSP页面的taglib标签的uri属性来引用-->
    <uri>http://skye/jsp/jstl/core</uri>

    <!--描述自定义的HelloSimpleTag标签-->
    <tag>
        <!--标签的名字,在JSP页面上使用标签时的名字-->
        <name>hello</name>

        <!--标签所在的全类名-->
        <tag-class>tagTest.HelloSimpleTag</tag-class>
        <!--标签体的类型-->
        <body-content>empty</body-content>
    </tag>

</taglib>

3.在 JSP 页面中导入和使用自定义标签

<%--
  Created by IntelliJ IDEA.
  User: Skye
  Date: 2017/12/13
  Time: 14:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://skye/jsp/jstl/core" prefix="skye" %>


<html>
<head>
    <title>Title</title>
</head>
<body>

<%--<c:forEach items="${requestScope.customers}" var="customer">
    ${customer.id}, ${customer.name}, ${customer.age}<br>
</c:forEach>--%>

<skye:hello/>

</body>
</html>

  

 

 

 

posted @ 2017-12-13 16:43  SkyeAngel  阅读(219)  评论(0)    收藏  举报