I want to prevent XSS attacks in my web app, so I want to escape the data entered by the user in a form before save it on the DB to show it in another JSP page, and I am hesitating between 2 approaches:
StringEscapeUtils.escapeHtml()
, that for the input REGGAETON / SALSA give me the same result,
but for ESAPI.encoder().encodeForHTML()
that for the same input the output will be REGGAETON & #x2f; SALSA
Do not save escaped data, escape it when you need to display it:
The way to escape it depends of the context you wants to display it, so if you save it escaped, it will be only usable in that context, and most of the time, escaping functions are not bijectives, so you will loose information.
For the way to encode it to display it in an html context, both ways seams correct.
Additionally, to improve the protection against XSS, you should look into CSP (content security policy), it helps a lot, especially for new projects.