XSS Cross-Site Scripting – Java Backend Security
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
XSS occurs when attacker-controlled data reaches a browser context that treats it as markup or code. For example, a comment saved in the database can become stored XSS if a page inserts it with innerHTML. A search value reflected into an unsafe template can become reflected XSS, while client-side code can create DOM-based XSS without the server rendering HTML at all.
The injected script runs with the application's origin. It can read page content, capture input, alter the UI, and send authenticated API calls. An HttpOnly cookie hides the cookie value from JavaScript, but it does not stop the script from using the logged-in page to perform actions.
The fix follows the output context. Use template escaping and textContent for text, safe URL construction for links, and avoid placing untrusted text directly inside JavaScript or CSS. If the application intentionally accepts rich HTML, sanitize it with a maintained allowlist. A restrictive Content Security Policy adds another barrier but does not replace safe sinks and encoding.
XSS Cross-Site Scripting – Java Backend Security
Direct Answer
Cross-Site Scripting (XSS) occurs when attacker-controlled data reaches a browser execution context without the protection that context requires. The browser then runs attacker code with the page's origin and can read visible data, change the page, call authenticated APIs, or capture user input. Stored, reflected, and DOM-based describe where the data is stored or processed. Prevent it with safe templating and DOM APIs, context-aware output encoding, HTML sanitization only when rich HTML is allowed, and a restrictive CSP as defense in depth.
Common Mistakes & Pitfalls
- Confusing XSS with SQL injection: XSS runs in the victim's browser; SQLi runs in the database.
- Thinking only the attacker is affected: stored XSS hits every user who views the page.
- Relying on input validation alone: encode at output in the correct context — the same data is safe in one place and dangerous in another.
- Using
th:utext/innerHTMLwith user data: these render raw HTML and re-open the hole. - Forgetting HttpOnly cookies: marking the session cookie
HttpOnlystops JavaScript from reading it, limiting cookie theft.
Check your understanding
Answer these without looking back at the article.
- What's the difference between stored, reflected, and DOM-based XSS?
- Why is output encoding the fix rather than input validation alone?
- How does an HttpOnly cookie reduce the impact of an XSS attack?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.