How to use both single and double quotes inside JSTL/EL expression?

19,351

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.

Share:
19,351
Dims
Author by

Dims

Software developer &amp; Machine Learning engineer C/C++/Java/C#/Python/Mathematica/MATLAB/Kotlin/R/PHP/JavaScript/SQL/HTML/ LinkedIn: http://www.linkedin.com/in/dimskraft Telegram: https://t.me/dims12 I prefer fishing rod over fish.

Updated on June 04, 2022

Comments

  • Dims
    Dims almost 2 years

    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
    Dims over 12 years
    Yes, thanks will probably use it. Was wondering anyway if JSTL/EL has such a feature lack.
  • BalusC
    BalusC over 12 years
    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.
  • Dims
    Dims over 12 years
    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
    Dims over 12 years
    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?
  • BalusC
    BalusC over 12 years
    Also XML? For that JAX-RS was invented. Caching can just be delegated to persistence layer.
  • Dims
    Dims over 12 years
    So what advantages over JSPs it has in situation like mine -- to have few adaptor services for different clients?
  • BalusC
    BalusC over 12 years
    Check the JAX-RS example in this answer: stackoverflow.com/questions/7874695/servlet-vs-restful/…
  • Dims
    Dims over 12 years
    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.