Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic attributes in a jsp tag

Tags:

java

jsp

I want to have a tag with dynamic attributes, like simple html tags, e.g. something like this:

<tags:superTag dynamicAttribute1="value" someOtherAttribute="valueOfSomeOther"/>

And in my implementation of tag I want to have something like this:

public class DynamicAttributesTag {

    private Map<String,String> dynamicAttributes;

    public Map<String, String> getDynamicAttributes() {
        return dynamicAttributes;
    }

    public void setDynamicAttributes(Map<String, String> dynamicAttributes) {
        this.dynamicAttributes = dynamicAttributes;
    }

    @Override
    protected int doTag() throws Exception {
        for (Map.Entry<String, String> dynamicAttribute : dynamicAttributes.entrySet()) {
            // do something
        }
        return 0;
    }
}

I want to point out that these dynamic attributes are going to be written by hands in a jsp, not just passed as Map like ${someMap}. So is there any way to achieve this?

like image 276
Artem Malinko Avatar asked Jun 09 '15 10:06

Artem Malinko


1 Answers

You will have to enable dynamic attributes in your TLD, like so:

<tag>
    ...
    <dynamic-attributes>true</dynamic-attributes>
</tag>

And then have your tag handler class implement the DynamicAttributes interface:

public class DynamicAttributesTag extends SimpleTagSupport implements DynamicAttributes {
    ...
    public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {
        // This gets called every time a dynamic attribute is set
        // You could add the (localName,value) pair to your dynamicAttributes map here
    }
    ...
}
like image 194
icke Avatar answered Nov 08 '22 10:11

icke