日期:2014-05-16  浏览次数:20363 次

jsp开发迭代标签一

第一步:编写一个标签处理器类

public class ForeachTag1 extends SimpleTagSupport {

//用来作为关键字存放值
private String var;
private Object items;

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

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

public void doTag() throws JspException, IOException {

List list=(List)items;
Iterator iterator=list.iterator();
while(iterator.hasNext())
{
Object obj=iterator.next();
this.getJspContext().setAttribute(var, obj);
this.getJspBody().invoke(null);
}
}
}

第二步:WEB-INF 目录下编写一个*.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>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>SimpleTagLibrary</short-name>
    <uri>http://www.liyong.foreach1tag</uri>
   <tag>
    <name>foreach1</name>
    <tag-class>com.liyong.foreach.ForeachTag1</tag-class>  
    <body-content>scriptless</body-content>
    <attribute>
    <name>items</name>
    <required>true</required>
    <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
    <name>var</name>
    <required>true</required>
    <rtexprvalue>false</rtexprvalue>
    </attribute>
</tag> 

<tag>

</taglib>

第三步:编写jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.liyong.foreach1tag" prefix="foreach"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'foreach1.jsp' starting page</title>

<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>
 
  <body>&nbsp;<br>
    <%
List list=new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
request.setAttribute("list",list);
%>
<foreach:foreach1 var="str" items="${list}" >
${str }
</foreach:foreach1>

  </body>
</html>
第四步:测试...