How to escape double quotes in JSTL function / EL?

后端 未结 3 1407
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 06:18

I need to change \" to \\\" with JSTL replace function to use the string in input tag like:



        
相关标签:
3条回答
  • 2020-12-29 06:29

    You may have a typo: I don't see a closing paren in there. Try this:

    ${fn:replace(news.title, "\"", "\\\"")}
    

    Also, are you trying to OUTPUT the results or are you trying to update news.title so the next time you access news.title the replacement is in place? This will work to output the result, but not to replace the actual value: news.title will not be changed by this call.

    0 讨论(0)
  • 2020-12-29 06:35

    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)}">
    

    See also:

    • XSS prevention in JSP/Servlet web application
    0 讨论(0)
  • 2020-12-29 06:44

    You are doing it wrong (with fn:replace).

    The correct way is:

    <input type="hidden" name="text" size="40" value="<c:out value='${text}'/>">
    (actually tested code - works 100%)
    

    Edit: Upon more thinking:

    • the way by using fn:escapeXml (as written by BalusC) works too and looks nicer (no nested tags)
    • using fn:replace to mimick fn:escapeXml is asking for trouble. You will forget to include some character that should be escaped. Just use the existing, tried and tested fn:escapeXml (or c:out)
    0 讨论(0)
提交回复
热议问题