解答例 - 実習課題4 - 7.繰り返し機能を持つカスタムタグ
(実習課題4)
実習課題3のタグ・ハンドラクラスを改良しなさい。
- 「IterationTag」インタフェースではなく、「TagSupport」クラスから作成するようにする事。
解答例
/* * ArrayTag.java TECHSCORE Java JSP7実習課題4 * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.jsp.chapter7.exercise4; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.IterationTag; import javax.servlet.jsp.tagext.TagSupport; public class ArrayTag extends TagSupport implements IterationTag { private Iterator iterator = null; public void setArray(Object[] objects) { List list = new LinkedList(); for (int i = 0; i < objects.length; i++) { list.add(objects[i]); } iterator = list.iterator(); } public int doStartTag() throws JspException { return (EVAL_BODY_INCLUDE); } public int doAfterBody() throws JspException { JspWriter writer = pageContext.getOut(); if (iterator.hasNext()) { try { writer.println(iterator.next() + "<br>"); } catch (IOException e) { e.printStackTrace(); } return (EVAL_BODY_AGAIN); } else { return (SKIP_BODY); } } }
<!-- taglib.jsp --> <!-- TECHSCORE Java JSP 7章 実習課題4 --> <!-- 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章 実習課題4</title></head> <body> <h3>JSP7章 実習課題4</h3> <% String[] str = new String[5]; str[0] = "test1"; str[1] = "test2"; str[2] = "test3"; str[3] = "test4"; str[4] = "test5"; %> <myTag:arrayTag7_4 array="<%= str %>"> </myTag:arrayTag7_4> </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>arrayTag7_4</name> <tag-class>com.techscore.jsp.chapter7.exercise4.ArrayTag</tag-class> <body-content>JSP</body-content> <attribute> <name>array</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>