JSP : JSTL's <c:out> tag

JavaJspJstlTags

Java Problem Overview


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>

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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)

Solution 4 - Java

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

Solution 5 - Java

Older versions of JSP did not support the second syntax.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve KuoView Question on Stackoverflow
Solution 1 - JavakrosenvoldView Answer on Stackoverflow
Solution 2 - JavaalexmeiaView Answer on Stackoverflow
Solution 3 - JavaChris SerraView Answer on Stackoverflow
Solution 4 - JavaGreenhornView Answer on Stackoverflow
Solution 5 - JavaWill WagnerView Answer on Stackoverflow