Search code examples
javajspjakarta-eejsp-tagstaglib

passing an array from a custom tag attribute


I'm trying to pass an integer array in an attribute of my custom tag. Here is what i've done so far.

hello.tld

<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>2.1</jsp-version>
    <short-name>helloTag</short-name>
    <uri>/WEB-INF/lib/hello</uri>
    <tag>
        <name>arrayIterator</name>
        <tag-class>bodyContentPkg.ArrayIterator</tag-class>
        <bodycontent>JSP</bodycontent>
        <attribute>
            <name>array</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

ArrayIterator.java

package bodyContentPkg;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

    public class ArrayIterator extends BodyTagSupport{
        int count;
        int[] myArray;
        int returnValue;

        public int[] getArray(){
            return myArray;
        }

        public void setArray(int[] myArray){
            this.myArray=myArray;
        }

        @Override
        public int doStartTag() throws JspException {
            count=0;
            return EVAL_BODY_INCLUDE;
        }

        @Override
        public int doAfterBody() throws JspException {
            if(count==myArray.length-1){
                returnValue=SKIP_BODY;
            }
            else{
                returnValue=EVAL_BODY_AGAIN;
                if(count<myArray.length){
                    JspWriter out = pageContext.getOut();
                    try {
                        out.println(myArray[count]);
                    } catch (IOException e) {
                            e.printStackTrace();
                    }
                }
                count++;
            }
            return returnValue;
        }
    }

bodyContent.jsp

<%@taglib prefix="cg" uri="/WEB-INF/lib/hello.tld" %>
<%pageContext.setAttribute("myArray", new int[] {1,2,3,4,5,6});%>
<cg:arrayIterator array="${myArray}"></cg:arrayIterator>

when i run the jsp file i get a blank page. dont know whats wrong.

Another question would be how to directly pass the array from the tag attribute without having to set the pageContext's attribute and avoiding to write a scriptlet? Thanks


Solution

  • when i run the jsp file i get a blank page. dont know whats wrong.

    You are using the tag without any body content and hence doAfterBody() is not called . Change the tag to something like this :

    <cg:arrayIterator array="${myArray}">&#160;</cg:arrayIterator>