<c:out> is a JSTL core tag, which is used for displaying server-side variables and hardcoded values on the browser (client). You may be wondering that a variable’s value and data can be displayed using Expression language(EL) and out implicit object too then why do we need <c:out> jstl tag? the difference is that the <c:out> tag escapes HTML/XML tags but others don’t, refer the example to understand this.
Tag <c:out> Example
In this example we are displaying a string on the browser, however we are using html tags in the value and we want to see what would be the result and how it is gonna HTML tags.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>c:out Tag Example</title> </head> <body> <c:out value="${'<b>This is a <c:out> example </b>'}"/> </body> </html>
Output:
<b>This is a <c:out> example </b>
escapeXml attribute of <c:out> tag
Let’s say I modify the above code like this – I have just added escapeXML attribute in the tag and marked it false. By default the value of escapeXML attribute is true. Since we have marked it as false it would not escape HTML/XML tags and the tags will work.
<c:out value="${'<b>This is a <c:out> example </b>'}" escapeXml="false"/>
Output:
Attribute “default” of <c:out> tag
Above we have seen escapeXML attribute of the <c:out> tag. There is another attribute “default” for this tag, which is used to display the fallback or default value in case the value of the <c:out> tag is null. Here is the example where we are trying to print the value of string str using the tag and since the string str value is null, the tag is printing the value set in default attribute.
<%! String str = null; %> <c:out value="${str}" default="default value of c:out"/>
Leave a Reply