Security operations

How to Fix Cross-Site Scripting (XSS) in Java: A Practical Guide

XSS in Java is fixed mainly at render time, not at input time. Learn contextual encoding, sanitizing, headers and testing so the same flaw does not come back.

Cysoro Security TeamPublished · 10 min read
<script> alert(1) </script> <img onerror= alert(1)> Blocked Encode.forHtml(userInput) Encode at the sink HTML · attribute · script · URL SECURITY OPERATIONS Fix XSS in Java Encode, sanitize, then verify.
Quick answer

Fix cross-site scripting in Java by encoding every untrusted value for the exact context where it is rendered, using the OWASP Java Encoder or your template engine's escaping, sanitizing any HTML you must accept, and adding Content Security Policy and HttpOnly cookies as extra layers. Then test with reflected and stored payloads and re-scan after every fix.

Key takeaways

  • Output encoding is the main fix: encode for HTML, attribute, JavaScript, URL or CSS context, not with one generic escape.
  • Use the OWASP Java Encoder, JSTL c:out or your framework's auto-escaping, and sanitize rich text with an allow-list sanitizer.
  • CSP, HttpOnly cookies and security testing are defense in depth, not substitutes for encoding.

A Java app can pass every functional test and still hand an attacker a script execution flaw. Cross-site scripting happens when untrusted data reaches a page and the browser treats it as code. The fix is mostly boring, repeatable encoding work — and that is good news, because it can be checked, tested and automated.

What is cross-site scripting in Java?

Cross-site scripting, or XSS, is a flaw where untrusted data is rendered in a web page and the browser runs it as script. In a Java app the data often comes from a request parameter, a form field, a database row or another service, and it is printed without encoding.

The classic example is a search page that echoes the search term back in the results heading. If the term is <img src=x onerror=alert(1)> and the page prints it raw, the browser builds an image element and runs the handler. The Java code did not intend to run script; it just mixed data with markup.

XSS is catalogued as CWE-79, improper neutralization of input during web page generation. It sits in the injection family in the OWASP Top 10. The impact depends on the session: an attacker who runs script in a victim's browser can steal session cookies that are not HttpOnly, perform actions as that user, deface pages or redirect the victim.

What are the three types of XSS?

The three types are reflected, stored and DOM-based XSS. They differ in where the untrusted value travels, and that changes where you look for the flaw and where the fix belongs.

TypeWhere the data travelsTypical Java exampleWhere to fix it
ReflectedRequest straight back in the responseSearch term echoed in resultsEncode at render time
StoredSaved, then shown to later usersComment or profile name in a listEncode every time it is displayed
DOM-basedNever reaches the server; client script writes it to the pageJavaScript reads location.hash and sets innerHTMLUse safe DOM APIs such as textContent

Reflected XSS needs the victim to click a crafted link. Stored XSS is more dangerous because one saved payload can hit every user who views the page, including admins. DOM-based XSS lives in your front-end JavaScript, so a server-side fix alone will not close it.

All three share one root cause: data and code were mixed. Your job is to separate them again, at the exact point where data becomes HTML, JavaScript, a URL or CSS.

How do you find the XSS flaw first?

Start from the scanner report or the proof of concept, then trace the value from its source to its sink. The source is where untrusted data enters, and the sink is where it is written into a page.

List every source: request parameters, headers, cookies, form fields, file uploads, database values, search results and responses from other services. Then list every sink: JSP output, servlet PrintWriter calls, template variables, JSON embedded in HTML, and JavaScript that writes to the DOM.

Reproduce the issue in a test environment with a harmless payload such as <script>alert(1)</script> or an image tag with an onerror handler. Note the exact field, the exact page and whether the payload is reflected, stored or DOM-based. A fix that does not match the type will look done and still be exploitable.

Do not test on productionRun payloads only in a test environment you own or have written permission to test. A stored payload left in production can fire for real users and admins.

Why does encoding have to match the context?

Encoding must match the output context because data that is safe in an HTML body is not safe in a JavaScript string, a URL or a style attribute. Each context has its own dangerous characters and its own safe encoding.

HTML-encoding a value inside a script block does not help, because the browser parses it as JavaScript, not HTML. URL-encoding a value inside an HTML attribute does not stop an attacker breaking out of the quotes. One generic escape function applied everywhere is a common reason fixes fail a retest.

Use the right method for each place the value lands. The OWASP Java Encoder gives you a method per context, and the table below maps the common cases.

Output contextOWASP Java Encoder methodExample
HTML bodyEncode.forHtml<p>Encode.forHtml(name)</p>
HTML attributeEncode.forHtmlAttributevalue="Encode.forHtmlAttribute(name)"
JavaScript block or variableEncode.forJavaScriptAssign an encoded string inside a script
URL parameterEncode.forUriComponentEncode the query value, not the whole URL
CSS valueEncode.forCssStringEncode a value placed in a style string
JSON stringEncode.forJsonEncode each JSON string value
Encode at the sink, for the right contextUntrusted datarequest, database,another serviceEncode itforHtml, forHtmlAttribute,forJavaScript, forUriBrowser seesplain text,not codeNever encode once at input and trust it forever. Encode where the value is rendered.
Contextual encoding turns untrusted data into harmless text at the point it is rendered. Illustration by Cysoro.

If you remember one rule, make it this one: "encode at the sink, for the context". Encode where the value leaves your code and enters a page, and pick the encoder for that exact spot.

How do you fix XSS with the OWASP Java Encoder?

Add the OWASP Java Encoder to your project and call the right Encode method at each sink. Version 1.6.0 provides a zero-dependency core, String and Writer APIs, and optional JSP adapters, and it runs on Java 8 and later.

For an HTML body, wrap the value: Encode.forHtml(userInput). That turns < into &lt; and > into &gt;, so the browser shows the characters as text instead of building elements from them. For an attribute, use Encode.forHtmlAttribute(userInput) and always quote the attribute value.

For JavaScript, prefer not to embed untrusted data in script at all. If you must, use Encode.forJavaScript for a JavaScript string, or put the data in a script type="application/json" block and parse it with JSON.parse. For JSON string content, use Encode.forJson and supply the double quotes yourself, or use a proper serializer for a whole JSON document.

For URLs, encode the parameter value with Encode.forUriComponent, and validate the scheme of any user-supplied link. Reject javascript: and data: URLs; allow only http:, https: and mailto: where a link is expected.

How do you fix XSS in JSP, Spring Boot and servlets?

In JSP, use <c:out value="${userInput}" />, which escapes output by default. Never use <%= userInput %> for untrusted data, because that prints the raw value. In a servlet, do not write user data with PrintWriter without encoding it first.

In Spring Boot with Thymeleaf, output is escaped by default, so th:text is safe and th:utext is the dangerous opt-out. Search your codebase for th:utext, th:attr with untrusted values, and any place you build HTML by string concatenation. Each one needs a review, not a blanket search-and-replace.

Spring Security adds several protective headers by default, including X-Content-Type-Options and X-Frame-Options. Those headers help, but they do not encode your output. Keep the framework defaults on, and treat them as a second layer, not the fix.

If your app serves a JavaScript front end, fix the client side too. Use textContent instead of innerHTML for untrusted text, use safe DOM methods to create elements, and never pass user data into eval, innerHTML or an event-handler attribute.

How do you handle fields that must accept HTML?

Some fields genuinely need HTML, such as a rich-text comment box or a product description. Encoding would break them, so you need sanitizing instead — and the two are not the same job.

Use an allow-list sanitizer such as the OWASP Java HTML Sanitizer. Define exactly which tags and attributes are allowed, for example b, i, p, a with href, and strip everything else, including script tags and event-handler attributes such as onerror. Build the policy with HtmlPolicyBuilder and call policy.sanitize(userSuppliedHtml).

Never write your own sanitizer with a block-list or a regular expression. Attackers have many ways around a list of bad tags, including mixed case, encoded characters and nested tags. An allow-list fails closed: anything you did not explicitly permit is removed.

Sanitize on input and encode on output. Even after sanitizing, encode the value for its render context where it is displayed as text, and validate link URLs in sanitized HTML so a link cannot carry a javascript: scheme.

Two different jobs: encode text, sanitize HTMLPlain text fieldEncode it: Encode.forHtmlName, search term, commentshown as text onlyNo tags should ever runRich text fieldSanitize it: allow-list onlyBold, links and paragraphsallowed; script and handlersstripped outPick the wrong tool and the fix either breaks the feature or leaves the hole open.
Encoding is for text; allow-list sanitizing is for HTML you must accept. Illustration by Cysoro.

What role does input validation play?

Input validation is a useful first layer, but it is not the fix for XSS. Validate early, with an allow-list: accept only the characters, length and format a field should have, and reject the rest.

For a username, that might be letters, digits and a few safe characters, up to a set length. For an email address, validate the format and then still encode it when it is displayed. For a number, parse it as a number and reject anything that is not one. Normalizing the input first, for example with java.text.Normalizer, helps stop encoded characters slipping past a check.

Validation fails as a sole defense because data can enter through another path: a bulk import, a partner feed, an admin tool or a database row written before validation existed. SEI CERT puts it plainly in IDS50-JG: output sanitizing is as important as input validation, because validated data does not stay validated for its whole lifetime.

So validate at the door and encode at the window. Both matter, and neither replaces the other.

How do CSP and security headers help?

Content Security Policy is your safety net. It tells the browser which sources may load scripts, styles and images, so even if an attacker injects a script, a strict policy can stop it running.

Use a nonce-based CSP where you can: generate a random nonce per response, allow scripts only with that nonce, and set object-src 'none' and base-uri 'self'. A host allow-list alone is weaker, because one permitted host with a JSONP endpoint or an old library can reintroduce execution.

Set HttpOnly and Secure flags on session cookies. HttpOnly stops client-side script reading the cookie, which limits what an attacker gains from a successful XSS attack. Add X-Content-Type-Options: nosniff so the browser does not guess a content type and treat a text response as script.

Check your live headers with the free security headers checker after you deploy. It shows which headers are present and which are missing, so you can confirm the fix reached production and not just your local machine.

How do you test the fix and stop it coming back?

Retest every sink you changed, with the original payload and with variants for each context. A payload that is harmless in an HTML body may still work in an attribute, a script block or a URL, so test each context separately.

Run your scanner again and confirm the finding is closed, then test in a real browser. Scanners can miss DOM-based XSS and can report a fix that only works for one encoding. Also check that normal content still works: names with apostrophes, search terms with quotes and comments with punctuation should display correctly.

Prevent recurrence with code review and automation. Add the OWASP Java Encoder to new code by default, ban raw output in your review checklist, and add tests that feed a script payload into each form and assert that the rendered page contains the encoded form, not the raw tag.

Keep dependencies current. The encoder, your template engine and Spring Security all receive fixes over time, and an old version can carry a bypass that a new version closes. The OWASP Java Encoder project page lists the current release and its supported contexts.

If you want a wider check of your site after the code fix, run the SSL checker alongside the headers check. The SecureFlag guide to XSS in Java is a good second reference for the rules above.

Review your broader website security posture too, so a fixed XSS flaw is not followed by an unpatched header or certificate issue.

For a related server-side flaw that often appears in the same reports, see our guide to spear phishing — attackers who cannot inject script often try to trick a user into running it for them.

The bottom line

Fixing XSS in Java is not a single patch. It is a habit: encode every untrusted value for its exact context, sanitize the HTML you must accept, and let CSP and HttpOnly cookies catch what slips through.

Start with the highest-risk sinks — search, comments, profile pages and admin screens — then work through the rest of the app and add a test for each one. You can verify the header half of the fix in seconds with the free security headers checker.

Frequently asked questions

What is cross-site scripting in Java?

Cross-site scripting, or XSS, is a flaw where untrusted data is rendered in a web page and the browser runs it as script. In Java apps it usually happens when a servlet, JSP or template prints a request parameter, a database value or an API value without encoding it for its output context.

What is the best way to fix XSS in Java?

Use contextual output encoding everywhere untrusted data is rendered. The OWASP Java Encoder is the standard choice, with Encode.forHtml for HTML body text, Encode.forHtmlAttribute for attributes, Encode.forJavaScript for script data and Encode.forUriComponent for URL parameters.

Does input validation fix XSS in Java?

No, not on its own. Input validation helps by rejecting unexpected values, but stored data, data from other systems and data that bypasses validation can still reach a page. Encoding at render time is the reliable fix, because it protects the page even when bad data gets in.

How do I fix stored XSS in Java?

Encode stored values every time they are displayed, not only when they are saved. Sanitize rich-text fields on input with an allow-list sanitizer such as the OWASP Java HTML Sanitizer, store the cleaned value, and still encode it at render time for its context.

Does Spring Boot protect against XSS automatically?

Spring Boot and Thymeleaf escape HTML by default in most templates, which removes many reflected and stored XSS flaws. You are still at risk if you use unescaped output, build HTML by string concatenation, use innerHTML in JavaScript, or pass user data into JavaScript, URLs or CSS without encoding.

What is the OWASP Java Encoder?

It is a small OWASP library for contextual output encoding in Java. Version 1.6.0 supports Java 8 and later, has a zero-dependency core, and provides methods for HTML, attributes, JavaScript, CSS, URLs and JSON. It is the recommended replacement for hand-written escaping and for older ESAPI encoding calls.

Can Content Security Policy fix XSS?

CSP cannot fix the underlying flaw, but a strong nonce-based policy can stop many injected scripts from running. Treat CSP as a safety net. Fix the encoding first, then add CSP, HttpOnly and Secure cookie flags, and X-Content-Type-Options.

How do I test that an XSS fix works in Java?

Re-run the original payload, try stored and reflected variants, test each output context separately, and run your scanner again. Also test with a browser, not only a scanner, and check that legitimate content still renders correctly after encoding.

Sources

  1. OWASP — OWASP Java Encoder
  2. Pentex Security — How to Fix Cross Site Scripting Vulnerability in Java
  3. SEI CERT — IDS50-JG. Properly encode or escape output
  4. SecureFlag — Cross-Site Scripting in Java
  5. Fluid Attacks — Stored cross-site scripting (XSS) - Java Fix
  6. Veracode Community — How to fix Improper Neutralization of Script-Related HTML Tags (CWE-80)
Written & fact-checked byCysoro Security Team

The engineers and analysts who build Cysoro's domain scanner, email-authentication checks and free security tools. We test what we write about every day — SPF, DKIM, DMARC, certificates, look-alike domains and phishing — and check each guide against the relevant standards, government guidance and vendor documentation.

  • Email authentication
  • Phishing & BEC
  • Domain & DNS security
  • Small-business security

Checked against the OWASP Java Encoder project page, SEI CERT IDS50-JG and the SecureFlag Java XSS guide.

How we write and fact-check →

Free tools for this topic

No account needed.

See where your domain stands

Free for up to 3 domains. No card, no installs.

Start free