Security

XSS in Java Web Applications: How to Prevent It

XSS in Java occurs when user-supplied data is rendered directly in HTML responses without encoding. Servlets and Spring MVC apps building HTML with string concatenation are especially vulnerable.


❌ Vulnerable Servlet

@WebServlet("/search")
public class SearchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String query = req.getParameter("q");
        resp.getWriter().println("<h1>Results for: " + query + "</h1>");
    }
}

✅ Safe with OWASP Encoder

import org.owasp.encoder.Encode;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String query = req.getParameter("q");
        resp.getWriter().println("<h1>Results for: "
            + Encode.forHtml(query) + "</h1>");
    }
}
💡

Pro tip: Spring's Thymeleaf auto-escapes in all th:text expressions by default. Only th:utext renders raw HTML — use it only with explicitly sanitized content.

Paste this code into LearnCodeGuide

Detect Java vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Java Code →

Related Guides

Java Sql InjectionJava Command InjectionJavascript Xss