Is nesting a c:out JSTL tag inside an element attribute a good practice or is using the var attribute of c:out generally preferred? It seems to work either way, but I suspect nesting it might not work in some application servers or versions of JSP (and it just looks wrong).
For example, an input element which has its value restored on validation failure, and with special character escaping:
<input type="text" name="firstname" value="<c:out value="${param.firstname}"/>"/>
versus:
<c:out value="${param.firstname}" var="firstname"/>
<input type="text" name="firstname" value="${firstname}"/>
I usually use the ${}
everywhere that I can. It's simple and more readable. I use <c:out>
when I need the extra functionality, such as the escapeXml
function.
In your example, you could actually get away with no <c:out>
:
<input type="text" name="firstname" value="${param.firstname}"/>
My answer does not address the XSS holes that BalusC and StuartWakefield mention. Although my answer is simplistically correct, you really should always mitigate XSS holes. I prefer to use the OWASP taglib.
<span>${esc:forHtml(sketchyText)}</span>
<span><esc:forHtml(sketchyText)/></span>
<input value="${esc:forHtmlAttribute(sketchyText)}"/>
The common practice to prevent XSS attacks in HTML element attributes without disturbing the well formed XML syntax by a nested <c:out>
tag is using fn:escapeXml()
function instead:
<input type="text" name="firstname" value="${fn:escapeXml(param.firstname)}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With