I need to change "
to \"
with JSTL replace function to use the string in input tag like:
<input type="hidden" name="text" size="40" value="${text}">
If the ${text}
has the "
, the HTML will be broken.
So I tried
<input type="hidden" name="text" size="40" value="${fn:replace(text, "\"", "\\\""}">
and
<input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '\"'}">
but didn't worked. The page makes errors like
org.apache.el.parser.ParseException: Encountered " "}" "} "" at line 1, column 32. Was expecting one of: "." ... ")" ... "[" ... "," ... ">" ... "gt" ... "<" ... "lt" ... ">=" ... "ge" ... "<=" ... "le" ... "==" ... "eq" ... "!=" ... "ne" ... "&&" ... "and" ... "||" ... "or" ... "*" ... "+" ... "-" ... "/" ... "div" ... "%" ... "mod" ...
How can I do this?
Update
I missed a close paren of replace function. The right one was this one with a close paren:
<input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '\"')}">
Update2
I found out that when posting texts, using \
is not a good idea because of this reason why can't use \" in HTML input tag?. The code should be like this:
<input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '"')}">
It doesn't work because the \
is an escape character in Java string. To represent it literally, you need to escape it with another \
again. Also the "
is a special character in EL, you also need to escape it to represent it literally. So, the proper syntax would have been:
<input type="hidden" name="text" size="40" value="${fn:replace(text, '\"', '\\\"'}">
But, you should actually be using fn:escapeXml()
to prevent XSS. It not only escapes quotes, but also other characters.
<input type="hidden" name="text" size="40" value="${fn:escapeXml(text)}">