解答例 - 実習課題1 - 7.繰り返し機能を持つカスタムタグ
(実習課題1)
7.1のサンプルカスタムタグ「ListTag」を実装し、それを使用したJSPページを作成しなさい。
解答例
/* * ListTag.java TECHSCORE Java JSP7実習課題1 * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.jsp.chapter7.exercise1; import java.util.Iterator; import java.util.List; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.IterationTag; import javax.servlet.jsp.tagext.Tag; public class ListTag implements IterationTag { private PageContext pageContext = null; private Tag parent = null; private Iterator iterator = null; private String item = ""; public void setList(String name) { List list = (List) pageContext.findAttribute(name); this.iterator = list.iterator(); } public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } public int doStartTag() throws JspException { if (iterator.hasNext()) { pageContext.setAttribute(item, iterator.next()); return (EVAL_BODY_INCLUDE); } else { return (SKIP_BODY); } } public int doAfterBody() throws JspException { if (iterator.hasNext()) { pageContext.setAttribute(item, iterator.next()); return (EVAL_BODY_AGAIN); } else { return (SKIP_BODY); } } public int doEndTag() throws JspException { return (EVAL_PAGE); } public void release() { } public void setItem(String item) { this.item = item; } public Tag getParent() { return parent; } public void setParent(Tag parent) { this.parent = parent; } }
<!-- taglib.jsp --> <!-- TECHSCORE Java JSP 7章 実習課題1--> <!-- Copyright (c) 2004 Four-Dimensional Data, Inc. --> <%@page contentType="text/html; charset=Windows-31J" import="java.util.*" %> <%@taglib uri="http://www.techscore.com/tags/myTag" prefix="myTag" %> <html> <head><title>JSP7章 実習課題1</title></head> <body> <h3>JSP7章 実習課題1</h3> <% List list = new LinkedList(); list.add(new String("test1")); list.add(new String("test2")); list.add(new String("test3")); list.add(new String("test4")); application.setAttribute("list", list); %> <table border="1"><tr> <myTag:listTag list="list" item="item"> <td><%= pageContext.getAttribute("item") %></td> </myTag:listTag> </tr></table> </body> </html>
<?xml version="1.0" ?> <!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.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>example tags</short-name> <tag> <name>listTag</name> <tag-class>com.techscore.jsp.chapter7.exercise1.ListTag</tag-class> <body-content>JSP</body-content> <attribute> <name>list</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>item</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>