2

I need to escape " and \ in jsp, but not necessarily in the same time.

With <c:out var="${value}" /> I can escape " character.

With ${fn:replace(value,'\\','&#92;')} I can escape the \ character, and is working fine.

I tried to handle both cases as follows.

I tried to use

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

but is not working, is not accepted, seems to be an error.

I also tried to put in a variable the string after replace, and after that using it in c:out, but was the same thing.

If anyone has an idea of a way to handle both cases, please let me know.

Note: the input comes from Java, that's why I used \\, and is sent forward as JSON. Thanks

John
  • 576
  • 1
  • 6
  • 14

2 Answers2

3

You could call fn:replace() twice, chaining the calls, to replace both characters.

${fn:replace(fn:replace(value,'\\','&#92;'),'\"','&#34;')}

It's not very pretty, though.

Tap
  • 6,332
  • 3
  • 22
  • 25
  • Yes, is a good idea, but I need escaping other characters too with `c:out`. I don't know why to two don't work together. – John Oct 21 '13 at 06:16
  • Yeah, that could get ugly if you have lots of characters to replace. So your objective is to have a proper JSON string? You might want to do this outside of the jsp with a java library like [Jackson](http://jackson.codehaus.org/) or [Gson](http://code.google.com/p/google-gson/). Or if the string is coming not from Java objects but from a back end, write a custom tag to do the exact formatting that you need. – Tap Oct 21 '13 at 12:54
  • Yep, I fixed at last. I used `org.apache.commons.lang.StringEscapeUtils`, which has methods for both escaping `HTML` and `Javascript`. Thanks for your help anyway. – John Oct 21 '13 at 14:35
  • Good to know. You should answer your own question to let others know how to solve the problem. – Tap Oct 21 '13 at 14:42
1

I found the best solution to be StringEscapeUtils from Apache, and I had to create a taglib as @Tap said, and added jar file commons-lang to project . This has a lot of functions for working with strings.

More details can be found here ->

Community
  • 1
  • 1
John
  • 576
  • 1
  • 6
  • 14