XSS Cross-Site Scripting – Java Backend Security
Fast recall
Quick revision
Core answer
th:text, use textContent in the browser, encode for the exact output context, and avoid building HTML or JavaScript with concatenation. When users must author rich HTML, sanitize it with a maintained allowlist policy before inserting it as HTML. Add a tested nonce- or hash-based CSP and hardened cookies as extra layers; they do not replace safe rendering.Interview-ready guide
Interview answer
I prevent XSS by making sure attacker-controlled values remain data instead of becoming browser code. In a Thymeleaf page, th:text is the normal choice because it escapes text. In JavaScript, textContent is safer than innerHTML for plain text. I avoid concatenating untrusted values into HTML, script, style, or event-handler strings.
The required handling depends on the output context. HTML text, attributes, URLs, JavaScript, and CSS use different parsers, so one generic escaping function is not enough. Often the best fix is an API that keeps the value out of executable code entirely. URL schemes and redirect targets also need allowlist validation.
When the product intentionally supports rich HTML, I use a maintained sanitizer with a narrow policy before rendering it. I then add a tested CSP, ideally using nonces or hashes for scripts, and harden cookies. Those layers reduce impact, but safe sinks and context-aware handling remain the main defense.
XSS Cross-Site Scripting – Java Backend Security
Direct Answer
Prevent XSS by keeping untrusted data out of executable browser sinks. Let Thymeleaf escape text with th:text, use textContent in the browser, encode for the exact output context, and avoid building HTML or JavaScript with concatenation. When users must author rich HTML, sanitize it with a maintained allowlist policy before inserting it as HTML. Add a tested nonce- or hash-based CSP and hardened cookies as extra layers; they do not replace safe rendering.
Common Mistakes & Pitfalls
- Escaping input on the way in: you don't know the output context yet, and double-encoding garbles data. Encode at output.
- Blocklisting
<script>: bypassed byonerror=,<img>, casing, and nesting. Use allowlist sanitization for HTML. - Wrong-context encoding: HTML-escaping data that lands inside a
<script>or a URL doesn't protect it — match the context. th:utext/innerHTMLwith user data: re-introduces the hole. Preferth:text/textContent.- Forgetting cookie flags: without HttpOnly, injected JS can read the session cookie.
Check your understanding
Answer these without looking back at the article.
- Why encode at output time instead of sanitizing at input time?
- When would you use the OWASP Java HTML Sanitizer instead of plain escaping?
- How does a Content-Security-Policy act as a second line of defense?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.