tags:

views:

716

answers:

2

I am writing some nested custom tags using JSP. I understand there are two ways to do this: 1) to write tag handler that extends BodyTagSupport, 2) to write a tag file.

In the 1st method, code is ugly. And I couldn't find a way to incorporate current struts tags.If I write the following using a JspWriter, I get this string in final HTML output instead of a meaningful output generated by the compiled JSP.

 <bean:write name="label">

So, I turned to the 2nd method, I wrote tag files. Then the above issue is solved. However, I then have problem getting a tag's parent tag, since I don't know the parent tag class. I could do the following if I wrote my own tag handler,

    ParentTag parent = 
        (ParentTag)findAncestorWithClass(this, ParentTag.class);
      if (parent == null) {
        throw new JspTagException("this tag is outside of its parent tag");
      }

But since, I used tag files instead, I don't quite know what class its parent is.

How could I solve this problem?

A: 

I was stupid enough to have forgetten that I could insert the above Java code into a JSP, and set a parameter on the page to pass the "parent" to the JSP page...

I am not sure, if I should close this question then. Because the answer is somewhat stupid. Senior StackOverflow users please advise.

tomato
A: 

Well, a Tag file isn't a "class" per se like a Tag Handler (I mean, obviously it is, like all JSP files, but, you get my meaning).

When I have to do "nested" tags with tag files, what I do is I put my state data in to the request under a "well know name". Effectively a shared "secret" between the two tags.

For example in one tag file I might do:

<%
jspContext.setAttribute("_myWellKnownName", new java.util.LinkedHashMap(), PageContext.REQUEST_SCOPE);
%>

Then, in a later tag file:

<%
    java.util.LinkedHashMap map = (java.util.LinkedHashMap) jspContext.findAttribute("_myWellKnownName");
%>

Then I manipulate that variable all I want.

In the parent tag, the executes the code of the child tags, so after my map (in this case) has been populated and I can do whatever I need to do with it at that point.

The basic pattern I find is to gather the results of the child tags in to something like a list and then the parent renders the actual data to the page after the children have done all their work.

I haven't had a need in my tags where I have parents nested within other parents (i.e. where one tag will conflict with the state of another), tho obviously that can be a problem with this method in a general sense. Still effective for my purposes though.

Will Hartung