Question

I am trying to use custom tag with variables.
for eg)
<c:forEach var="test" items="itemstest">
${test}
</c:forEach>

In the above code i am able to access the test value inside the <c:forEach> tag.
I need to create a custom tag with similar functionality.
I have got info from the oracle docs http://docs.oracle.com/javaee/5/tutorial/doc/bnamu.html under title Declaring Tag Variables for Tag Handlers.
Can anyone pls help me to implement the same with example.

Was it helpful?

Solution

Hi i have solved it in the following way

class: test.java    
    public void doTag() throws JspException, IOException {
    getJspContext().getOut().flush();
    //any method or operation
    super.doTag();
    getJspContext().setAttribute(variable, "Hello");
}

Create getter setter for variable

tld file:  
<tag>
    <name>test</name>
    <tag-class>com.org.test</tag-class>
    <body-content>empty</body-content>
    <attribute>
        <name>inputValue</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <name>variable</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

jsp file:
       <%@ taglib uri="/WEB-INF/tld/tldfilename.tld" prefix="tag" %>
       <tag:test inputValue="hello" variable="testValue"/>
       ${testValue}

OTHER TIPS

For something so simple, you may be better off using tag files, which makes it easy to create a tag library using some small additions to the normal jsp syntax (and is part of the standard)

http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPTags5.html

A "tag with variables" is done using an attribute declaration, JSP code is quite simple:

<%@tag pageEncoding="utf-8" %>
<%-- dont forget to add declaration for JSTL here -->
<%@attribute name="test" type="java.lang.String" required="true" %>
<c:forEach var="test" items="itemstest">

    ${test}

</c:forEach>

See the linked documentation on whre to put and name the files to make them accessible within you own jsp files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top