Search code examples
jspescapingjstlspecial-characters

JSTL escaping special characters


I have this weird issue with special characters. In JSP, I am using field name as id and the name can be anything like

id="<1 and &>2" (OR)
id="aaa & bbb"

I don't have any other option to use ID's other than names, that what the only thing I get from backend.

So, Is there any logic to remove all the special characters using JSTL. With the present scenario, In JS I will do some operations with the ID. this is causing many issues for each kind of browser.

Please suggest, Thanks in advance...


Solution

  • The JSTL provides two means of escaping HTML special chars :

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    […]
    <c:out value="${myName}"/> 
    

    and

    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    […]
    ${fn:escapeXml(myName)}
    

    Both wil transform the special chars into their respective HTML entities : (< becomes &lt;, & become &amp;...).

    Note that the IDs must be encoded in HTML, but not in JavaScript.