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

不羁岁月 提交于 2019-12-10 10:22:58

问题


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?


回答1:


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)




回答2:


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']}"/>


来源:https://stackoverflow.com/questions/762588/how-do-i-make-dynamic-attributes-work-in-jsp-tag-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!