第九章自定义标签第五节简单标签

简单标签是简化第四节;
iterateSimple.jsp

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
 <%@ taglib prefix="please" uri="/WEB-INF/lang.tld"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title heretitle>
<%
   List people = new ArrayList();
   people.add("王小二2");
   people.add("思思光2");
   people.add("草泥马2");
   pageContext.setAttribute("people", people);
%>
head>
<body>
     <please:iterate items="people" var="p">
     <h2>${p }h2>
     please:iterate>

body>
html>

IterateSimpleTag.java

package com.lang.tag;

import java.util.List;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.tagext.TagSupport;

public class IterateSimpleTag extends SimpleTagSupport{



    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String var;
    private String items;



    public String getVar() {
        return var;
    }


    public void setVar(String var) {
        this.var = var;
    }



    public String getItems() {
        return items;
    }


    public void setItems(String items) {
        this.items = items;
    }



    @Override
    public void doTag() throws JspException, IOException {
        Object value = this.getJspContext().getAttribute(items);
        if (value!=null && value instanceof List) {
            Iterator iter = ((List)value).iterator();
            while (iter.hasNext()) {
                this.getJspContext().setAttribute(var, iter.next());
                this.getJspBody().invoke(null);//响应页面
            }
    }

    }
}

lang.tld



<taglib xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">
    <tlib-version>1.0tlib-version>
    <short-name>pleaseTagshort-name>

    <tag>
       <name>iterate2 name>
       <tag-class>
          com.lang.tag.IterateSimpleTag
       tag-class>
       <body-content>scriptlessbody-content>
       <attribute>
         <name>varname>
         <required>truerequired>
         <rtexprvalue>truertexprvalue> 
       attribute>
       <attribute>
         <name>itemsname>
         <required>truerequired>
         <rtexprvalue>truertexprvalue> 
       attribute>
    tag>
taglib>

运行结果:
第九章自定义标签第五节简单标签_第1张图片

你可能感兴趣的:(jsp/servlet,标签)