I would like to escape characters in JSP pages. Which is more suitable, escapeXml
or escapeHtml
?
The fn:escapeXml() function escapes characters that can be interpreted as XML markup.
The escapeHtml function is designed to accept a string input of text and return an escaped value to interpolate into HTML.
To prevent the conversion, escapeXml should be explicitly set to false as follows: <c:out value="${product.listPrice}" escapeXml="false" /> Another common scenario is the display of user-supplied text, such as product descriptions or dynamic text messages.
JSTL fn:escapeXml() FunctionThe fn:escapeXml() function escapes the characters that would be interpreted as XML markup. It is used for escaping the character in XML markup language. The syntax used for including the fn:escapeXml() function is: java.
They're designed for different purposes, HTML has lots of entities that XML doesn't. XML only has 5 escapes:
< represents "<"
> represents ">"
& represents "&"
' represents '
" represents "
While HTML has loads - think of
©
etc. These HTML codes aren't valid in XML unless you include a definition in the header. The numeric codes (like ©
for the copyright symbol) are valid in both.
There's no such thing as escapeHtml
in JSP. You normally use <c:out escapeXml="true">
(it by the way already defaults to true
, so you can omit it) or fn:escapeXml()
to escape HTML in JSP.
E.g.
<c:out value="Welcome, ${user.name}" />
<input name="foo" value="${fn:escapeXml(param.foo)}" />
It will escape them as XML entities which works perfectly fine in plain HTML as well. They are only literally called XML entities because HTML entities are invalid in XML.
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