ServletJsp之自定义标签

来源:互联网 发布:淘宝霸气收货人名字 编辑:程序博客网 时间:2024/04/28 04:20

这次我们尝试在JSP中自定义一个标签,通过这个标签来遍历集合。
首先我们建立自定义标签类IterateSimpleTag:

public class IterateSimpleTag extends SimpleTagSupport {    @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());                getJspBody().invoke(null); // 响应页面            }        }    }    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;    }}

注意get和set方法一定要有,系统会自动调用。
下面我们在WEB-INF中添加一个tag.tld文件,用来注册标签类。

<?xml version="1.0" encoding="UTF-8" ?><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.0</tlib-version>    <short-name>iterateTag</short-name>    <tag>         <name>iterateSimple</name>         <tag-class>            com.tth.tag.IterateSimpleTag         </tag-class>         <body-content>scriptless</body-content>         <attribute>             <name>var</name>             <required>true</required>             <rtexprvalue>true</rtexprvalue>         </attribute>         <attribute>             <name>items</name>             <required>true</required>             <rtexprvalue>true</rtexprvalue>         </attribute>    </tag></taglib>

最后我们再JSP中来调用这个标签:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="tag" uri="/WEB-INF/tag.tld"%><%@ page import="java.util.*"%><!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><%    List people = new ArrayList();    people.add("1");    people.add("1124");    people.add("1235235");    people.add("12352523523");    pageContext.setAttribute("people", people);%></head><body>    <tag:iterateSimple items="people" var="p">        <p>${p }</p>    </tag:iterateSimple></body></html>
1 0