121

Writing a JSP page, what exactly does the <c:out> do? I've noticed that the following both has the same result:

<p>The person's name is <c:out value="${person.name}" /></p>
<p>The person's name is ${person.name}</p>
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257

5 Answers5

161

c:out escapes HTML characters so that you can avoid cross-site scripting.

if person.name = <script>alert("Yo")</script>

the script will be executed in the second case, but not when using c:out

Mdhar9e
  • 1,376
  • 4
  • 23
  • 46
krosenvold
  • 75,535
  • 32
  • 152
  • 208
  • 2
    Only if 'escapeXML' it set to true (not sure if it is by default) – Chris Serra Nov 14 '08 at 19:12
  • 17
    I believe it is true by default. – Zack The Human Jul 02 '09 at 17:02
  • 7
    N.B. it escapes XML not HTML. One of the more annoying subtleties of JSTL. I end up always writing my own HTML escape EL fn. – Adam Gent Jun 12 '11 at 18:16
  • 5
    The attribute name is case sensitive so it's escapeXml="true" not escapeXML – Mark Chorley Apr 08 '13 at 10:43
  • 2
    I have no idea what this answer's code sample is showing- can someone clarify? It mentions a "second case" but I don't see that and I don't see c:out being used in the code. – IcedDante Oct 02 '14 at 15:22
  • 2
    @IcedDante: the first case is the first code line mentioned by OP with the c:out. The second case is OP's second line of code – riddle_me_this Oct 05 '14 at 20:33
  • 1
    @AdamGent What problem do you solve by using your own HTML escape fn? – David Balažic Sep 27 '18 at 06:51
  • @DavidBalažic I don't use JSP anymore but: 1. attribute content escaping is different than text/tag content so you need two different functions even for the case of XML other wise the whitespace is ignored and 2. XML escaping is slightly different than HTML and this is why commons lang and various other libraries have different functions. – Adam Gent Oct 05 '18 at 12:42
130

As said Will Wagner, in old version of jsp you should always use c:out to output dynamic text.

Moreover, using this syntax:

<c:out value="${person.name}">No name</c:out>

you can display the text "No name" when name is null.

jpaugh
  • 6,634
  • 4
  • 38
  • 90
alexmeia
  • 5,241
  • 4
  • 24
  • 24
7

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

Chris Serra
  • 13,226
  • 3
  • 25
  • 25
6

You can explicitly enable escaping of Xml entities by using an attribute escapeXml value equals to true. FYI, it's by default "true".

Greenhorn
  • 328
  • 2
  • 6
  • 12
4

Older versions of JSP did not support the second syntax.

Will Wagner
  • 4,128
  • 3
  • 22
  • 14