Sunday, April 3, 2011

How to Escape Character in EL with JSTL tag?

I have this JSP code snippet:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<c:choose>
  <c:when test="${var1.properties[\"Item Type\"] eq \"Animal's Part\"}">
    <c:set var="cssClassName" value="animalpart" />
  </c:when>
  <c:otherwise>
    <c:set var="cssClassName" value="" />
  </c:otherwise>
</c:choose>

The JSP cannot be compiled by the server. However, if I remove the character "'" from "Animal's Part", it is compilable. I tried to escape it by using "\" character but it still gives me error.

Any suggestion/help is appreciated. I tried to avoid using scriptlet if possible.

Thanks.

EDIT: I managed to get it working (after posting to StackOverflow), posted as one of the solution in this question. I tried other solution posted before that (by Vincent and Eddie), however, unfortunately, none works in my environment, although I reckon that they might works in the answers' environment. Thanks.

From stackoverflow
  • try this

    <c:when test='${var1.properties["Item Type"] eq "Animal\'s Part"}'>
    
  • Use escapeXml="false" For example:

    <c:out value="${formulario}" escapeXml="false" />
    
  • You have two easy choices:

    <c:when test="${var1.properties['Item Type'] eq 'Animal\'s Part'}">
    
    <c:when test='${var1.properties["Item Type"] eq "Animal\'s Part"}'>
    
  • Hi, this is the solution that works in my use case:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    
    <c:set var="itemType"        value="${var1.properties[\"Item Type\"]}" />
    <c:set var="item_animalpart" value="Animal's Part" />
    <c:set var="item_treepart"   value="Tree's Part" />
    
    <c:choose>
      <c:when test="${itemType eq name_item_animalpart}">
        <c:set var="cssClassName" value="animalpart" />
      </c:when>
      <c:when test="${itemType eq name_item_treepart}">
        <c:set var="cssClassName" value="treepart" />
      </c:when>
      <c:otherwise>
        <c:set var="cssClassName" value="" />
      </c:otherwise>
    </c:choose>
    

0 comments:

Post a Comment