I have a string that users are able to enter on the internet, currently it is not protected against XSS attacks. I would like to be able to replace < and > symbols. Commonly known as 'less than', 'more than', 'angle brackets' etc.
I am sure this has been asked a million times but I can't find a simple answer. I assume regex is the way forward but can't work out how to pick these characters.
You really should use StringEscapeUtils.escapeHtml()
from Apache Commons Lang to instead of regex for this. E.g. all you need to do is:
String escaped = StringEscapeUtils.escapeHtml(input);
The best practice to protect against XSS is to escape all HTML entities and this method handles those cases for you. Otherwise you'll be writing, testing and maintaining your own code to do what has already been done. See the OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With