JSTL escaping special characters

2019-02-05 20:40发布

问题:

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

回答1:

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

${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.



回答2:

I think your question was misunderstood. I arrived at the same point as you, and got the problem solved with excapeXml="false".

<c:out value="${id}" escapeXml="false"/> 

I had data in database like:

&lt;Hello World&gt;

and escapeXml="false" made it display

<Hello World>


回答3:

I think this is what you are lokking for

Use Spring's HtmlUtils.htmlEscape(String input).



回答4:

I just faced a scenario where I had to escape ' i.e. Single Quote apart from other special characters. In that case fn:escapeXml failed. So I used JavaScriptUtils.javaScriptEscape() of Spring API, created a tag and applied. Now the issue is resolved. I also referred the URL : http://www.coderanch.com/t/528521/JSP/java/Passing-JSTL-variable-special-characters.