Archive for August, 2008

JSP Comments within Comments

Monday, August 4th, 2008
Have you ever run into that frustrating situation where you have JSP comments in your code, and need to comment out a large block of code that
contains those comments.  The situation looks something like this:

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

<c:if test=”${!empty param.userInput}”>
<%– Trim the userInput –%>
<c:set var=”trimmedUserInput” value=”${fn:trim(param.userInput)}”>
</c:if>

<html>
<form action=”.”>

<p>
-${param.userInput}–${trimmedUserInput}-
</p>

<p>
User input: <input type=”text” name=”userInput” value=” Some Input.
“>
</p>
<p>
<input type=”submit”>
</p>
</form>
</html>

Now say you wanted to comment out the <c:if> block for testing ... the
problem is this won't work:

<%–
<c:if test=”${!empty param.userInput}”>
<%– Trim the userInput –%>
<c:set var=”trimmedUserInput” value=”${fn:trim(param.userInput)}”>
</c:if>
–%>

because the inner comments "break" the outer comments (it's just not legal
syntax).  What to do?  A nice way to deal with this is to use the following
syntax for your general comments:

<% // Trim the userInput %>

You can legally wrap that syntax with <%-- --%> style comments!  So the
above code, with the test comments included would look like:

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

<%–
<c:if test=”${!empty param.userInput}”>
<% // Trim the userInput %>
<c:set var=”trimmedUserInput” value=”${fn:trim(param.userInput)}”>
</c:if>
–%>

<html>
<form action=”.”>

<p>
-${param.userInput}–${trimmedUserInput}-
</p>

<p>
User input: <input type=”text” name=”userInput” value=” Some Input.
“>
</p>
<p>
<input type=”submit”>
</p>
</form>
</html>

Happy documenting!