Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call JSP tag dynamically by name

Tags:

dynamic

jsp

tags

Is there a way to use JSP custom tags dynamically? I have a variable that represents the name of the tag and I want to call the tag but to avoid switch statements.

Example: I have tags <my:foo attr="fooAttr" /> and tag <my:bar attr="barAttr" />, than I have <c:set var="tagName" value="foo" />. I want to somehow use the tagName variable to call the tag .

like image 305
Mihajlo Brankovic Avatar asked Jan 28 '15 13:01

Mihajlo Brankovic


1 Answers

I understand your concern... Something like <tags:${ tagname }/>, isn't it? Such a solution is tempting indeed, but it would involve modifying the JSP specification to accept dynamically named tags that aren't part of the XML specification.

A "semidynamic" but simple solution could consist in creating a tag that encapsulates the switching logic. It could look like:

<%@ tag body-content="empty" %>
<%@ attribute name="tagname" required="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="tags" %>

<c:choose>
  <c:when test="${ tagname == 'tag1'}">
    <tags:tag1/>
  </c:when>
  <c:when test="${ tagname == 'tag2'}">
    <tags:tag2/>
  </c:when>
</c:choose>

Then you could use (and reuse) it wherever you like using something like the following:

<tags:my-switch tagname="${ tagname }"/>

Of course, you can add any other attribute you might need, and the body of the tag doesn't need to be empty. In fact, if you need to process some tag body, modify the body-content attribute above and process the body using the <jsp:doBody/> standard tag.

Hope this will fulfil your needs...

Jeff

like image 181
Jeff Morin Avatar answered Oct 23 '22 09:10

Jeff Morin