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

2 Answers 2

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.

4
  • 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, 2013 at 6: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 or 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, 2013 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, 2013 at 14:35
  • Good to know. You should answer your own question to let others know how to solve the problem.
    – Tap
    Oct 21, 2013 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 ->

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.