XSS Cross-Site Scripting – Java Backend Security
Fast recall
Quick revision
Core answer
< into text in an HTML-text context. Sanitization parses allowed markup and removes or rewrites disallowed elements, attributes, and URLs. Use encoding or a safe text API for ordinary data. Use a maintained sanitizer only when valid rich HTML must remain markup. Neither is universal: the output context and allowed-content requirement decide the control.Interview-ready guide
Interview answer
Output encoding and sanitization solve different problems. Encoding represents a value so a particular output parser treats it as data. In an HTML-text context, for example, the less-than sign is encoded so a tag is shown rather than created. The encoder must match the actual context; HTML-text encoding does not automatically make a value safe inside JavaScript, CSS, or a URL.
Sanitization is for content that is supposed to remain HTML, such as a formatted article. A maintained sanitizer parses the fragment and keeps only the elements, attributes, and URL schemes allowed by policy. Removing the word script with a regex is not sufficient because browsers have many executable contexts.
For normal user text I choose a safe text sink such as th:text or textContent. For rich HTML I sanitize it and render it only in the intended place. Input validation can enforce length and business rules, but it does not replace output protection.
XSS Cross-Site Scripting – Java Backend Security
Direct Answer
Output encoding represents a value so one specific parser treats it as data, such as turning < into text in an HTML-text context. Sanitization parses allowed markup and removes or rewrites disallowed elements, attributes, and URLs. Use encoding or a safe text API for ordinary data. Use a maintained sanitizer only when valid rich HTML must remain markup. Neither is universal: the output context and allowed-content requirement decide the control.
Check your understanding
Answer these without looking back at the article.
- Why can't input sanitization alone fully prevent XSS?
- When is storing sanitized HTML actually the right choice?
- What does 'context-aware encoding' mean for an HTML attribute vs a script block?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.