Search code examples
javajspjstljspx

Conditional HTML attribute in JSPX


What's the right way to print an html attribute conditionally using JSPX?

These both throw validation errors on p tag:

    /* first try */

<p ${true ? 'name="foobar"' : ''}>hello</p>

    /* second one */

<c:set var="somevar" scope="page">
  <c:if test="${true}">
    name="foobar"
  </c:if>
</c:set>
<p ${somevar}>hello</p>

Element type "p" must be followed by either attribute specifications, ">" or "/>". at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:41)

EDIT: appended full code

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields" xmlns:form="urn:jsptagdir:/WEB-INF/tags/form" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:spring="http://www.springframework.org/tags" version="2.0">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <jsp:output omit-xml-declaration="yes"/>

    <p ${true ? 'name="foobar"' : ''}>hello</p>

</div>

Solution

  • The problem is that Jasper tries to validate well-formness of JSP before processing EL.

    This happens because JSPX extension that your file supposedly has means that it is a JSP Document. And JavaServer Pages Specification says:

    It is a translation-time error for a file that is identified as a JSP document to not be a well-formed, namespace-aware, XML document.

    I couldn't find any way to instruct Jasper to disable XML well-formness validation.

    The Ant task to pre-compile JSP files as described in Tomcat docs has got validateXml parameter. But it just skips checks for a valid XML, not for well-formed XML.

    So your options are either to rename your file to JSP, or add <is-xml>false</is-xml> to web.xml, or to follow @damo_inc's suggestion.