JSP - Can I use <jsp:attribute> inside <c:if>? Exception: “Must use jsp:body to specify tag body”

我只是一个虾纸丫 提交于 2019-12-07 01:58:25

问题


I have the following inside a JSP:

<c:if test="${true}">
<jsp:attribute name="extraInlineComplianceJavascript">
window.isSummaryComplianceLinkVisible = '${TabList.isSummaryComplianceLinkVisible}';
window.isDetailComplianceLinkVisible = '${TabList.isDetailComplianceLinkVisible}';
window.complianceSummaryReportTag = '${helper.complianceSummaryReportTag}';
window.complianceDetailReportTag = '${helper.complianceReportTag}';
</jsp:attribute>
</c:if>

As is, I get the following exception:

 Must use jsp:body to specify tag body for &lt;MyTag if jsp:attribute is used.

If I remove the outermost <c:if> tags, it works. Is there a problem with using <jsp:attribute> inside a <c:if> ? Any help would be appreciated. Thanks.


回答1:


The body of an element is defined implicitly as the body of the the respective element. The body can also be represented explicitly using <jsp:body>. This is required if one or more <jsp:attribute> elements appear in the body of the tag. Checkout the references for element, attribute and body.

But that is not the real problem. The problem is <jsp:attribute> does not play well with conditional tags. The <jsp:attribute> is trying to set the attribute on its parent tag, which in your example is <c:if>.

You could use <c:if> inside the element (as BalusC suggested in his comment), but that will result in a an attribute with an empty value, or you could go from:

<jsp:element ...>
  <c:if test="${true}">
    <jsp:attribute name="extraInlineComplianceJavascript">
      ....
    </jsp:attribute>
  </c:if>
</jsp:element>

to (a more verbose):

<c:if test="${true}">
  <jsp:element ...>
    <jsp:attribute name="extraInlineComplianceJavascript">
      ....
    </jsp:attribute>
  </jsp:element>
</c:if>
<c:if test="${false}">
  <jsp:element ...>
     <!-- no attribute for false -->
  </jsp:element>
</c:if>

You could also use a <c:choose>. And of course it won't work well with more than one attribute :D.

My personal suggestion would be to throw away the <jsp:attribute> and find another way to conditionally set your attributes.



来源:https://stackoverflow.com/questions/3507610/jsp-can-i-use-jspattribute-inside-cif-exception-must-use-jspbody-to

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