自定义标签库


////IteratorTag.java--------------------------
package liu;

import java.io.IOException;
import java.util.Collection;

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

public class IteratorTag extends SimpleTagSupport {
private String collectionAttribute;
private String item;
public String getCollectionAttribute() {
return collectionAttribute;
}
public void setCollectionAttribute(String collectionAttribute) {
this.collectionAttribute = collectionAttribute;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
@Override
public void doTag() throws JspException, IOException {
Collection itemList=(Collection)getJspContext().getAttribute(collectionAttribute);
for(Object s:itemList)
{
getJspContext().setAttribute(item, s);
getJspBody().invoke(null);
}


}


}
______________________iterator.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">
    <tlib-version>1.0</tlib-version>
    <short-name>liutag</short-name>
    <uri>http://www.liu.com/iterator</uri>
    <tag>
        <name>iterator</name>
<tag-class>liu.IteratorTag</tag-class>
<body-content>scriptless</body-content>

<attribute>
<name>collectionAttribute</name>
<required>true</required>
<fragment>true</fragment>
</attribute>
<attribute>
<name>item</name>
<required>true</required>
<fragment>true</fragment>
</attribute>
    </tag>
</taglib>

___________________iterator.jsp_______________________

<?xml version="1.0" encoding="GB18030" ?>
<%@ page language="java" contentType="text/html; charset=GB18030"   pageEncoding="GB18030"
import="java.util.*"%>
<%@ taglib uri="http://www.liu.com/iterator" prefix="liu" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<title>Insert title here</title>
</head>
<body>
<%
List<String> list=new ArrayList<String>();
list.add("hello");
list.add("liuhualiang");
list.add("java web program");
list.add("java is not so hard");
list.add("刘华良,加油");
list.add("有野心的人,眼下的困难不叫困难");
pageContext.setAttribute("list",list);
%>
<table border="1">
<liu:iterator collectionAttribute="list" item="liuitem">
<tr><td>${pageScope.liuitem}</td></tr>
</liu:iterator>
</table>


</body>
</html>

你可能感兴趣的:(java,jsp,xml,XHTML,servlet)