Question

I want to create a custom tag library but in the handler class I would like to have integer attributes.

In the tld file I have the following code:

<tag>
        <name>circle</name>
        <tag-class>draw.Circle</tag-class>
        <body-content>jsp</body-content>
        <attribute>
            <name>x</name>
            <required>true</required>
        </attribute>
</tag>

there are also other integer attributes, but this example is relevant for the others.

The handler class, for the moment looks this way:

public class Circle extends TagSupport{
    private Integer x;

    public Integer getX() {
        return x;
    }
    public void setX(String x) {
        this.x = Integer.parseInt(x);
        System.out.println("Set x");
    }
}

I haven't specified the attribute type in the tld file, and default it should be String. Though I get an error like this:

Unable to find setter method for attribute: x

I have also tried modifying the attribute type to: <type>java.lang.Integer</type> and the setter method to:

public void setX(int x) {
    } 

And I get the same error.

How should I define the attribute in the tld file and the setter in the handler class so that I don't get the setter error?

Was it helpful?

Solution

JSP custom tags use the JavaBeans technology, which has standard conventions (here's a small JavaBeans tutorial that captures the main aspects).

A "bean property" (see PropertyDescriptor) consists of a getter and / or a setter method of the same type (return type of the getter must match single param type of the setter), otherwise they are not mapped to the same bean property (I'm guessing the first method in the class "wins"). So your Integer getter / String setter approach can't work, as the String setter will not be detected as belonging to the Integer property).

Set the parameter type of the setter method to Integer and it will work, the conversion will be applied automatically, JavaBeans has built-in support for value conversion through the PropertyEditor interface (implementations for at least all primitive value types exist, and through auto-unboxing, Integer can be considered primitive).

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