Some XSS attacks can be prevented by using HTML Encoding.
HTML encoding function is built into many languages, In .NET WebUtility.HtmlEncode can do it, in PHP we can use htmlentites function, in Python cgi.escape can be used.
But there is no built-in function to do HTML Encode (or HTML Entities) in Java.
We can use Apache Commons Lang library to do this work.
1 2 3 |
import org.apache.commons.lang.StringEscapeUtils; System.out.println(StringEscapeUtils.escapeHtml("<>")); |
Above code will output following result using HTML Encoding
<>
Note that not all XSS attacks can be prevented by HTML encoding (https://stackoverflow.com/questions/53728/will-html-encoding-prevent-all-kinds-of-xss-attacks).