How To Avoid HTML Injection In Java

How To Avoid HTML Injection In Java

Avoiding HTML Injection in Java applications involves careful input validation, output encoding, and using secure libraries to sanitize any user-generated content before it’s rendered in HTML.

Here’s a clear guide specifically for Java:

πŸ›‘οΈ How to Avoid HTML Injection in Java

βœ… 1. Validate Input Data

  • Always validate inputs on the server side.
  • Accept only expected formats and characters (e.g., letters, numbers).
  • Reject or sanitize unexpected characters.

βœ… 2. Escape Output Properly

  • Before displaying user input in HTML pages, escape HTML special characters to prevent injection.
  • Use libraries like:
    • Apache Commons Text’s StringEscapeUtils.escapeHtml4()
    • OWASP Java Encoder Project (recommended)
javaCopyEditimport org.apache.commons.text.StringEscapeUtils;

String safeHtml = StringEscapeUtils.escapeHtml4(userInput);

Or using OWASP Java Encoder:

javaCopyEditimport org.owasp.encoder.Encode;

String safeHtml = Encode.forHtml(userInput);

βœ… 3. Use Templating Engines That Auto-Escape

  • Frameworks like Thymeleaf, JSP with JSTL, Freemarker, or Velocity escape output automatically.
  • Avoid concatenating strings directly into HTML.

βœ… 4. Avoid Inserting Raw User Input into HTML

  • Instead of building HTML with string concatenation, use template engines or DOM manipulation libraries.

βœ… 5. Sanitize Rich Text Inputs (if needed)

  • If your app accepts rich text (HTML) input, sanitize it before storing or displaying.
  • Use libraries like jsoup to whitelist allowed tags and attributes.

Example using jsoup:

javaCopyEditimport org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;

String clean = Jsoup.clean(userInput, Safelist.basic());

βœ… 6. Set Content Security Policy (CSP) Headers

  • Configure your web server or application to send CSP headers.
  • This limits what scripts/styles can run, reducing damage if injection occurs.

βœ… 7. Use Secure Frameworks and Keep Dependencies Updated

  • Use well-maintained frameworks with security features.
  • Regularly update libraries and frameworks to patch vulnerabilities.

βœ… 8. Use HTTPS

  • Protect data in transit to avoid tampering.

Summary Example (using OWASP Encoder in a servlet):

javaCopyEditimport org.owasp.encoder.Encode;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String userInput = request.getParameter("input");
    String safeOutput = Encode.forHtml(userInput);
    response.getWriter().write("<p>User input: " + safeOutput + "</p>");
}