How to Prevent XSS in Java Web Applications Step by Step
Prevent cross-site scripting in Java web apps with context-aware output encoding, safe template settings, a Content Security Policy and sanitizing rich text.

Cross-site scripting lets an attacker run JavaScript in your users' browsers by getting your site to print their input as markup. The script then acts as the user: it reads data, makes requests and steals sessions. In Java the standard defenses are in the template layer, and the dangerous moves are the ones that bypass it. This post covers each place output happens. It extends Java security basics.
The vulnerable shape
@GetMapping("/search")
@ResponseBody
String search(@RequestParam String q) {
return "<h1>Results for " + q + "</h1>"; // q = <script>alert(1)</script> runs in the browser
}The response is HTML, and q went straight into it. Anything the user typed is now markup.
Use the template engine's escaping
Thymeleaf escapes by default with th:text:
<p th:text="${comment}">...</p> <!-- safe: HTML-escaped -->
<p th:utext="${comment}">...</p> <!-- unsafe: raw HTML -->Treat th:utext and [(...)] inline unescaped output as a code smell, to be used only with sanitized HTML. JSP needs <c:out value="${comment}"/> or ${fn:escapeXml(comment)}; a bare ${comment} is not escaped in many JSP versions. JSF escapes h:outputText unless escape="false". Freemarker and Mustache have autoescaping options; verify they are on.
A @RestController returning JSON is safe from the HTML angle as long as the content type is application/json; the browser will not run it. Content sniffing and a wrong type bring risk back, so keep X-Content-Type-Options: nosniff (Spring Security's default).
Encode for the context
HTML escaping is not enough everywhere. The same value needs different encoding depending on where it lands:
| Context | Example | Encoding |
|---|---|---|
| HTML body | <p>VALUE</p> | HTML entity encoding |
| HTML attribute | <input value="VALUE"> | Attribute encoding, always quote the attribute |
| JavaScript | <script>var x = 'VALUE';</script> | JavaScript string encoding |
| URL parameter | href="/s?q=VALUE" | URL (percent) encoding |
| CSS | style="color: VALUE" | CSS encoding |
Avoid putting untrusted data into script blocks and inline event handlers at all. Pass data to scripts through data- attributes (HTML-encoded) or JSON endpoints. When you must encode by hand, use the OWASP Java Encoder library:
String safe = Encode.forHtml(userInput);
String inAttr = Encode.forHtmlAttribute(userInput);
String inJs = Encode.forJavaScript(userInput);Do not write your own replace("<", "<") chain; it misses contexts.
Rich text: sanitize with an allow-list
If users may submit formatted HTML (a comment editor), encoding would show the tags as text. Sanitize instead:
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String clean = policy.sanitize(userHtml);The OWASP Java HTML Sanitizer keeps allowed elements and removes scripts, event handlers and dangerous URLs such as javascript:. Sanitize on output or on input, but be consistent, and re-sanitize if the policy changes. Blacklist regular expressions fail against browser parsing quirks.
Defense in depth
Content Security Policy. A header that tells the browser which scripts may run:
http.headers(h -> h.contentSecurityPolicy(csp ->
csp.policyDirectives("default-src 'self'; script-src 'self'; object-src 'none'")));A strict policy blocks inline scripts and injected script sources even if a hole exists. It takes work with applications that use inline scripts.
HttpOnly and Secure cookies. server.servlet.session.cookie.http-only=true (the default) keeps script from reading the session cookie. Add secure and same-site.
Validate input shape. A field that should be a number should be parsed as one. This reduces the surface, and it is not a substitute for output encoding.
DOM-based XSS
Some XSS never touches the server: JavaScript on the page reads location.hash and writes it with innerHTML. Use textContent instead of innerHTML, and avoid eval and document.write with untrusted data.
Test for it
Add a test that submits <script>alert(1)</script> and "><img src=x onerror=alert(1)> to every field that is later displayed and asserts that the response contains the encoded form. A scanner (OWASP ZAP) run in CI finds missing cases.
The fix for the vulnerable controller
Back to the controller from the start. The fixed version returns a view and lets the template engine escape the value:
@Controller
class SearchController {
@GetMapping("/search")
String search(@RequestParam(defaultValue = "") String q, Model model) {
model.addAttribute("q", q);
model.addAttribute("results", index.search(q));
return "search";
}
}<h1>Results for <span th:text="${q}">query</span></h1>
<ul>
<li th:each="r : ${results}">
<a th:href="@{/items/{id}(id=${r.id})}" th:text="${r.title}">title</a>
</li>
</ul>A request with q=<script>alert(1)</script> now renders the characters <script> and the browser shows the text. Note the th:href with a path variable: Thymeleaf percent-encodes the id, so the link cannot carry a javascript: URL into the attribute either. If you still need to return HTML from a @ResponseBody, encode with the library and set the content type explicitly:
@GetMapping(value = "/search", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
String searchHtml(@RequestParam String q) {
return "<h1>Results for " + Encode.forHtml(q) + "</h1>";
}Passing data to JavaScript without opening a hole
A frequent mistake is inlining a server value into a script block. Even with HTML escaping, a value inside a JavaScript string needs a different encoding, and a quote or a closing script tag breaks out. Avoid the problem by moving data through an attribute that JavaScript reads:
<div id="app" th:data-user="${user.name}" th:data-config="${configJson}"></div>
<script src="/assets/app.js"></script>const app = document.getElementById('app');
const user = app.dataset.user; // plain string, no parsing of markup
const config = JSON.parse(app.dataset.config); // JSON from a trusted serializerThe attribute value is HTML-encoded by the template engine and decoded by the browser into a plain string. Nothing the user typed is ever parsed as script. If you must write a JSON blob into a script tag, put it in <script type="application/json"> and escape < as < in the serializer, so that a </script> inside a value cannot end the block.
A Content Security Policy with a nonce
The CSP shown earlier blocks all inline scripts. Pages that need one inline script can allow it with a per-request nonce, so an injected script, which cannot know the nonce, still does not run:
@Component
class CspNonceFilter extends OncePerRequestFilter {
private static final SecureRandom RANDOM = new SecureRandom();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
byte[] bytes = new byte[16];
RANDOM.nextBytes(bytes);
String nonce = Base64.getEncoder().encodeToString(bytes);
request.setAttribute("cspNonce", nonce);
response.setHeader("Content-Security-Policy",
"default-src 'self'; script-src 'self' 'nonce-" + nonce + "'; object-src 'none'; base-uri 'none'");
chain.doFilter(request, response);
}
}<script th:attr="nonce=${cspNonce}">
window.addEventListener('load', () => document.body.classList.add('ready'));
</script>The base-uri 'none' directive closes a quieter hole: an injected <base> tag that redirects every relative script URL to an attacker's server. Roll the policy out with the Content-Security-Policy-Report-Only header first, read the violation reports for a week and then enforce. A policy turned on blindly breaks a payment widget on a Friday.
Tests that catch regressions
Write the attack strings into a parameterized test, and assert on the encoded form in the response body:
@WebMvcTest(SearchController.class)
class SearchXssTest {
@Autowired MockMvc mvc;
@ParameterizedTest
@ValueSource(strings = {
"<script>alert(1)</script>",
"\"><img src=x onerror=alert(1)>",
"'-alert(1)-'",
"</title><svg onload=alert(1)>"
})
void reflectedInputIsEncoded(String payload) throws Exception {
String body = mvc.perform(get("/search").param("q", payload))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
assertFalse(body.contains("<script>alert(1)</script>"));
assertFalse(body.contains("onerror=alert(1)>"));
assertFalse(body.contains("<svg onload"));
}
}The assertions check that the raw payload does not appear, which is the property that matters. Add one case for each field that is displayed later, including ones that look harmless, like a display name or a filename.
Sanitizing stored rich text once
For a comment editor, sanitize on write and keep the clean result, so that every consumer, including the mobile app and the email digest, gets safe markup:
private static final PolicyFactory POLICY = new HtmlPolicyBuilder()
.allowElements("p", "br", "strong", "em", "ul", "ol", "li", "a", "code", "pre")
.allowUrlProtocols("https", "mailto")
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks()
.toFactory();
@Transactional
public Comment add(long postId, String html) {
return comments.save(new Comment(postId, POLICY.sanitize(html)));
}Store the sanitized value and render it with the unescaped output syntax, which is the one place th:utext is acceptable. Keep the policy in one class so a review of what users may write is a review of one file.
Where this does not apply
An API consumed only by a mobile app has no HTML context, but the app's web views may. The reference list of encoding rules is the OWASP XSS Prevention Cheat Sheet, and the OWASP Java Encoder project documents the library. For forged requests, a related but different attack, see preventing CSRF. The same escaping discipline applies to SQL, covered in SQL injection prevention, and to forged requests in CSRF prevention.


