JSP定制标记——用“脚本编程变量”取代bean来进行遍历

Tag13.java

package tag13;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.util.List;
import java.util.Iterator;

public class Tag13 extends BodyTagSupport {
private List lists;
private Iterator iters;
public void setLists(List lists){
this.lists = lists;
}
public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
public void doInitBody() throws JspException {
if (lists.size() <= 0) return;
iters = lists.iterator();
pageContext.setAttribute(this.id, iters.next());
}
public int doAfterBody() throws JspException {
if (iters.hasNext()) {
pageContext.setAttribute(this.id, iters.next());
return EVAL_BODY_AGAIN;
} else {
try {
bodyContent.writeOut(this.getPreviousOut());
} catch (IOException ioe) {
throw new JspException(ioe.getMessage());
}
}
return SKIP_BODY;
}
}

Info13.java

package tag13;

import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;

public class Info13 extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[] {
new VariableInfo(data.getId(),
"java.lang.Object",
true,
VariableInfo.NESTED)
};
}
}

tag13.tld

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC '-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN' 'http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd'>

<taglib>
<tlib-version>1.2</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>aaaaaaaaaaaaaaa</short-name>
<info>aaaaaaaaaa</info>
<tag>
<name>tag13</name>
<tag-class>tag13.Tag13</tag-class>
<tei-class>tag13.Info13</tei-class>
<body-content>JSP</body-content>
<attribute>
<name>id</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>lists</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

tag13.jsp

<%@ page contentType="text/html;charset=GBK" %>
<%@ taglib prefix="tag" uri="tag13.tld" %>
<%@ page import="java.util.List,
java.util.ArrayList"
%>

<html>
<body>
<%
List mylists = new ArrayList();
mylists.add("aaaaaaaaaaaaaaa");
mylists.add("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
mylists.add("ccccccccccccccccccccccccccccccccccc");
mylists.add("dddddddddddddddddddddddddddddddddddddddddddd");
%>
<table width="300" border="5">
<tag:tag13 id="iter" lists="<%=mylists%>">
<tr><td><%=iter%></td></tr>
</tag:tag13>
</table>
</body>
</html>

结果:

aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbb
ccccccccccccccccccccccccccccccccccc
dddddddddddddddddddddddddddddddddddddddddddd

分析:

1、在标记类中每次计算Body时,以标记类的ID为key保存bean到PageContext中,然后在JSP页面中直接访问这个bean。

2、由于标记类的ID属性由TagSupport类和BodyTagSupport类进行维护,因此程序员在自己定制的标记类中无须另设定一个ID属性。

你可能感兴趣的:(java,编程,bean,jsp,脚本)