4

I want to call fn:replace inside EL inside c:out to replace quote caracters.

The following does not work

<c:out value="${fn:replace(userName,'"','\\"')}"/>

because XML parser stops at first double quote and sees no c:cout tag termination (JSP compilation stage error).

The following

<c:out value="${fn:replace(userName,'&quot;','\\&quot;')}"/>

does not work, probably because replace function does not see actual quote character.

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

8

Parameterize them with <c:set>.

<c:set var="search" value='"' />
<c:set var="replace" value='\\"' />
<c:out value="${fn:replace(userName, search, replace)}"/>

Unrelated to the concrete question, have you still not considered a real JSON generator? With for example Gson it's a matter of the following oneliner, given that user is a fullworthy Javabean:

String json = new Gson().toJson(user);

You'll get syntactically valid JSON directly without fiddling all ways to get JSP/JSTL/EL to produce valid JSON.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Yes, thanks will probably use it. Was wondering anyway if JSTL/EL has such a feature lack. – Dims Jan 17 '12 at 20:24
  • Maybe you're just using the wrong tool for the job ;) JSP is merely a view technology designed to generate **HTML** dynamically. JSTL/EL are streamlined to suit that purpose. – BalusC Jan 17 '12 at 20:27
  • Hm... Sometimes I generate JSONs in iterating loop... I am sure Gson can handle this but am not feel it will be beautiful to collect data in temporary objects before sending... Also I am generating not only json but xml also... hence it was an idea to have a bunch of JSPs for all these interactions... – Dims Jan 17 '12 at 20:31
  • I don't think this is my fault that they didn't think how to escape quotes in quotes :) Also if JSP is for html only then what for they have created a content-type tag? – Dims Jan 17 '12 at 20:33
  • Also XML? For that JAX-RS was invented. Caching can just be delegated to persistence layer. – BalusC Jan 17 '12 at 20:34
  • So what advantages over JSPs it has in situation like mine -- to have few adaptor services for different clients? – Dims Jan 17 '12 at 20:41
  • Check the JAX-RS example in this answer: http://stackoverflow.com/questions/7874695/servlet-vs-restful/7875851#7875851 – BalusC Jan 17 '12 at 20:55
  • It looks good if all sides are under my control. For the case I need create predefined textual representation from predefined java objects it looks overcomplexed. – Dims Jan 17 '12 at 21:08