Search code examples
struts2jsp-tags

Creating a Struts2 tag from a custom tag


I'm trying to write a Struts2 tag to my JSP from a custom tag. I have the code below. Is this actually possible, or is there something about the JSP life cycle that makes this impossible? If it is impossible, is there another way to do what I'm trying to do?

        while (iterator.hasNext()) {
            Bulletin bulletin = (Bulletin) iterator.next();
            if (bulletin.isApproved()) {
                out.println("<s:url value=\"GetSingleBulletin\">");
                out.println("<s:param name=\"id\" " 
                        + "value=\"%{" + bulletin.getId()+ "}\" />");
                out.println(bulletin.getName() + " -- " + bulletin.getSubject() 
                        + " " + bulletin.getDate());
                out.println("</s:url>");
                out.println("<br><br>");
            }
        }

Solution

  • Tags are resolved as part of the "translation phase" that converts a JSP to a servlet. By emitting other tags in your tag, you are assuming a "2nd pass" translation, which does not happen. So it's fundamentally a bad idea.

    Instead, I would suggest just emitting the equivalent HTML (really just a URL with parameters, given your code above). Assuming your problem is no more complex than what you describe above, this seems like the simplest approach. In fact, even if you could emit tags, I don't see a very convincing case here for why tags would be better than raw HTML anyway. JSP taglibs are supposed to facilitate automation and less code where possible; less code reduces errors and makes JSPs more maintainable. But your case above is not one that screams out for "must use tags".

    Alternatively, if you would really prefer to use the tags you have in your custom tag above, or you would be willing to eliminate your taglib altogether, you could write the above Java code in a scriptlet and intersperse your use of the other struts tags in between that scriptlet code. So, something like:

    <%
            while (iterator.hasNext()) {
                Bulletin bulletin = (Bulletin) iterator.next();
                if (bulletin.isApproved()) {
    %>
                    <s:url value="GetSingleBulletin">
    etc.
    
    <%
                }
            }
    %>