Search code examples
jspjsp-tags

How can I give EL expressions as parameters in nested jsp 2.0 tags?


I want to do something like this to call a JSP 2.0 tag:

<mytags:foo abc="<%=def%>">
  <mytags:bar ghi="<%=jkl%>"/>
</mytags:foo>

Where Strings def and jkl are defined earielr in the jsp file. Suppose my tag files look like this:

foo.tag:

<%@ tag body-content="scriptless" %>
<%@ attribute name="abc" required="true" %>
<div class="${abc}">
  <jsp:doBody/>
</div>

bar.tag:

<%@ tag body-content="scriptless" %>
<%@ attribute name="ghi" required="true" %>
<div>${ghi}</div>

I want the output to look like this:

<div class="def">
<div>jkl</div>
</div>

(assuming the variables def and jkl were initialized to def and jkl, respectively, in the calling JSP file.)

The outer tag gets its attribute just fine (<div class="def">) but the inner one fails.

Is this possible? I am getting errors that jkl cannot be resolved.


Solution

  • Note the body-content="scriptless" attribute in the tag directive. This means that the body surrounded by the tag can't contain scriptlet code (the <% %> stuff). You need to use EL.

    It works for me if I change the stuff in the JSP to:

      <c:set var="def" value="def"></c:set>
      <c:set var="jkl" value="jkl"></c:set>
    
      <mytags:foo abc="${def}">
          <mytags:bar ghi="${jkl}"/>
      </mytags:foo>
    

    Note that I need to add <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>