JSTL notes

A few notes for a few common JSTL things so I don’t forget:


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


  <c:when test=””>
  <!--other when conditions -->

String replace using replace function:

${fn:replace(foo, '"', '\"')}

This next tip for using a loop varStatus to build HTML ids is from: http://stackoverflow.com/questions/6600738/use-jstl-foreach-loops-varstatus-as-an-id

<c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
  <div id="divIDNo${theCount}">

This unexpectedly gives:

<div id="divIDNojavax.servlet.jsp.jstl.core.LoopTagSupport$1Status@5570e2">

To get the actual varStatus id you need to use:

${theCount.index} gives value from 0
${theCount.count} gives value from 1

For example:

<div id="divIDNo${theCount.index}">


JSTL String test oddity

I’ve come across this multiple times, and for some reason this always catches me out. You’d think being that EL has ‘eq’ and ‘ne’ operators that work with Strings that this should work:

<c:if test="${hello.name ne ''}">
    Hello <c:out value="${hello.name}"/>

This seems to make sense that it would do what you think it should do, but no, it always returns true. The code you’re looking for is using EL operator ’empty’:

<c:if test="${!empty hello.name}">
    Hello <c:out value="${hello.name}"/>