Contextual Output Encoding

Output encoding is the process of replacing HTML control characters (e.g. <, >, ", &, etc) into their encoded representatives. This is the best mitigtion against cross-site scripting attacks.

Different contexts require different encoding types. Fortunately, there are two libraries out there to help you out. ESAPI Library from OWASP and StringEscapeUtils from Apache
 

For data rendered in Script context: <script>encode for javascript here</script> ESAPI.encoder().encodeForJavaScript or StringEscapeUtils.escapeJavaScript

For data rendered in HTML context: <body>encode for HTML here</body> ESAPI.encoder().encodeForHtml or StringEscapeUtils.escapeHtml

For data rendered in HTML Attribute context: <div id="encode for HTML attribute here" /> ESAPI.encoder().encodeForHTMLAttribute 

For data rendered in URL context: <img src="encode for URL here" /> ESAPI.encoder().encodeForURL 

For data rendered in CSS context: <style>Encode for css here</style> ESAPI.encoder().encodeForCSS