Alternatively, if your intent is to display user-controlled input back to the client, then you can also just replace all <
by <
and all >
by >
. This way the HTML won't be interpreted as-is by the client's application (the webbrowser).
If you're using JSP as view technology, then you can use JSTL's c:out for this. It will escape all HTML entities by default. So for example
will NOT display the alert, but just show the actual string as is.