In JSTL/JSP when do I have to use <c:out value="${myVar}"/> and when can I just say ${myVar}
Asked Answered
B

2

16

I've been doing this the whole time in my JSP code:

<c:out value="${myVar}"/>

Today I just realized for the first time that I seem to be able to use this shorter version just as well:

${myVar}

It works without <c:out>!

Perhaps this is because my page is declared like this:

<%@ page language="java" contentType="text/html; 
charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>

So, my question is, can I replace <c:out> in my code with this shorter version? Is there any reason to keep using <c:out>? Or are there places where I might still need it?

Bregenz answered 4/7, 2011 at 18:9 Comment(0)
S
26

<c:out> does more than simply outputting the text. It escapes the HTML special chars. Use it (or ${fn:escapeXml()}) every time you're not absolutely sure that the text doesn't contain any of these characters: ", ', <, >, &. Else, you'll have invalid HTML (in the best case), a broken page, or cross-site scripting attacks (in the worst case).

I'll give you a simple example so that you understand. If you develop a forum, and someone posts the following message, and you don't use <c:out> to display this message, you'll have a problem:

<script>while (true) alert("you're a loser");</script>
Spalding answered 4/7, 2011 at 18:13 Comment(3)
"Looser"? I think you mean "loser".Fakery
Does this also apply for when you're not directly outputting content to the page (eg: <c:set var="someVar" value="${someVal}"/>). Should ${someVal} in this case also be escaped? or do you only have to worry about escaping it when printing to the page (eg: <h1><c:out value="${someVar}"/></h1>)Pekin
Only when printing it to the page.Spalding
V
8

Perhaps this is because my page is declared like this:

<%@ page language="java" contentType="text/html; 
charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>

Untrue. Just <%@page pageEncoding="UTF-8" %> was been sufficient. The remnant is all already the default.

EL in template text is supported since JSP 2.0 which goes hand in hand with Servlet 2.4 (which was already out since 2003... keep yourself up to date). So when you're running a Servlet 2.4 capable container (e.g. Tomcat 5.5 or newer) with a web.xml declared conform Servlet 2.4 API, then you'll be able to use EL in template text.

However, you should not use it to (re)display user-controlled input. So, do not use it to (re)display (saved) request headers, request cookies, request URLs, request parameters, request bodies, etc. This will put doors open to XSS attacks.

Veto answered 4/7, 2011 at 20:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.