Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...