我想要一个具有动态属性的标签,例如简单的html标签,,例如像这样的东西:

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

在实现tag的过程中,我想要这样的东西:
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;
    }
}

我想指出的是,这些动态属性将由jsp手动编写,而不仅仅是像${someMap}这样的Map传递。那么有什么办法可以做到这一点?

最佳答案

您将必须在TLD中启用动态属性,如下所示:

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

然后让您的标记处理程序类实现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
    }
    ...
}

10-07 13:16