How Do I make dynamic-attributes Work in JSP Tag Files?

6.4k views Asked by At

So according to my JSP reference book, as well as every other reference I can find on the web, I'm supposed to be able to do something like:

<%@ tag dynamic-attributes="dynamicAttributesVar" %>

and then when someone uses an attribute that I didn't define in an attribute directive, I should be able to access that attribute from the "dynamicAttributesVar" map:

<%= dynamicAttributesVar.get("someUnexpectedAttribute") %>

However, that doesn't work, at all; I just get a "dynamicAttributesVar cannot be resolved" error when I try.

Now, I did discover (by looking at the generated Java class for the tag) that I can "hack" a working dynamic attributes variable by doing:

<% Map dynamicAttributesVar = _jspx_dynamic_attrs; %>

Now, that hack doesn't work unless I also use the dynamic-attributes parameter on my tag directive, so it seems that the parameter is doing something.

But what I want to know is, how can I make it do what it does for every other JSP user out there?

2

There are 2 answers

2
araqnid On BEST ANSWER

Isn't "dynamicAttributesVar" the name of the key in the page context that the dynamic attributes are put into? So you could do

<c:out value="${dynamicAttributesVar.someUnexpectedAttributes}"/>

or if you must use scriptlets:

Map dynamicAttributes = (Map) pageContext.getAttribute("dynamicAttributesVar")

(Disclaimer: I haven't tried it, I've just used dynamic attributes in tags with direct Java implementations... but it seems reasonable)

0
Bumptious Q Bangwhistle On

Just trying to get a badge for answering a four year old question.

I have this problem as well and came across some help at O'Reilly to use JSTL instead of scriptlets.

The original poster could have used this code to get all keys/values:

<c:forEach items="${dynamicAttributesVar}" var="a"> 
${a.key}="${a.value}" 
</c:forEach> 

This would get a specific value:

<c:out value="${dynamicAttributesVar['someUnexpectedAttribute']}"/>