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)
- Apache Commons Textβs
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>");
}