[ Team LiB ] Previous Section Next Section

Inserting Comments

Comments are generally used for two things: making notations about the code and removing sections of code. There are at least four different ways to add comments to a JavaServer Page, each with its own advantages and disadvantages. If your JSP is generating HTML, you can use HTML comments, which use the <!-- and --> tags, shown here:

<!-- This is an HTML comment. -->

In general, use HTML comments in a JSP only if you want the comment to be visible on the browser. Most of the time, you don't care whether the user can see any of your comments, so HTML comments are usually not used in a JSP. You might find yourself using HTML comments if you have a large section of HTML in your JSP and you want to remove a section temporarily. Although you can remove it with JSP comment tags (which you will learn about in a moment), it's nicer to keep the block pure HTML rather than turn it into a mixture of HTML and JSP tags. It will be easier to identify the source of a problem if you accidentally remove a comment start or end tag later on in your development.

Debugging with Comments


HTML comments can be useful if you want to include debugging information in the output of a page, without showing it to users. However, don't put anything sensitive in the comments.

Because any code you place inside the <% %> tags is Java code, you can use both of Java's commenting mechanisms. For example, you can do a one-liner comment, such as

<% // This is a one-line JSP comment. %>

You can also use the /* */ comment tags within separate <% %> tag pairs. This method is difficult to follow, and fortunately, there is a better way. Here is an example of using the /* and */ comment tags:

<% /* %>
  This is actually commented out.
<% */ %>

Not only is the commenting method confusing; it's also wasteful. When the JSP is translated, the text within the /* */ is still converted into Java statements that emit the text. However, because the Java statements are surrounded by /* */, they are ignored by the compiler.

JavaServer Pages have a special comment tag pair recognized by the JSP compiler. You can surround your comments with <%-- --%> to place a comment in your JSP code. The <%-- --%> prevents text from even being placed into the Java source generated by the JSP container. Here is an example of a JSP comment:

<%-- This comment will not appear in the servlet source code. --%>

If you need to remove a section of code from a JSP, the <%-- --%> tags are the best way to do it. They take priority over the other tags. In other words, if a <% %> tag pair occurs within the comment tags, the <% %> tag pair is ignored, as the following example shows:

    out.println("You will never see this.");
    [ Team LiB ] Previous Section Next Section