Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL escaping special characters [duplicate]

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

like image 357
Max Avatar asked May 26 '11 06:05

Max


4 Answers

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.

like image 144
JB Nizet Avatar answered Nov 19 '22 07:11

JB Nizet


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>
like image 29
James Avatar answered Nov 19 '22 07:11

James


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.

like image 2
RKH Avatar answered Nov 19 '22 06:11

RKH


I think this is what you are lokking for

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

like image 2
Ramesh PVK Avatar answered Nov 19 '22 05:11

Ramesh PVK