Best way to block XSS injection having decode and getParameter

Solution 1:

HtmlUtil.escape allows you to escape certain text so that it is safe to use in an HTML context.

As a drop in replacement you can use the different methods provided by the Apache commons-text library StringEscapeUtils class, especially the escapeXml** ones.

Please, in any way, consider read the documentation created by OWASP about Cross Site Scripting prevention.

It provides great insights about the different related types of attacks involved in the term, and how you can prevent or mitigate everyone of them.

The documentation provides references to several related libraries like the OWASP Java Encoder project and OWASP Java Html Sanitizer.

The first project gives you some examples for handling untrusted content in different scenarios.

The second one allows you for a more structured HTML processing based on user defined policies. Please, consider review the different examples provided in the Github repository.

If you require a full fledged prevention framework, you can use in your application the artifacts provided for ESAPI project, from OWASP as well.

There is nothing wrong with escaping the information you are receiving with classes like HtmtUtil in your server side code but, as you can see in the different examples provided, in order to prevent XSS related attacks, it is typical to perform some kind of encoding/escaping when outputting the HTML code fragment instead, when you are providing the information to your client: the important thing is to prevent that somebody may, for example, introduce a terminal </textarea> tag that terminates a textarea and then a <script>...</script> block with some malicious code next:

</textarea><script>alert('hello')</script>

The kind of server side processing you are describing is more frequently used when you want to prevent other types of code injection. Please, consider read this other documentation again from the OWASP website, I think it could be useful.