Examples / Server Examples / Escaping User Input

Escaping User Input

example java server servlets post libraries

This example uses an the Apache Commons Text library to escape user input. Learn more in the java server libraries tutorial.

index.html contains an HTML form:

<!DOCTYPE html>
<html>
  <head>
    <title>Form</title>
  </head>
  <body>
    <h1>Enter some input:</h1>
    <form action="/user-input-escaped/form" method="POST">
      <input type="text" name="data" value="<h1>oh no</h1>">
      <br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

FormServlet.java handles the POST request by escaping the user’s content and outputting it in the response:

package io.happycoding.servlets;

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.text.StringEscapeUtils;

@WebServlet("/form")
public class FormServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    String userInput = request.getParameter("data");
    String escapedUserInput = StringEscapeUtils.escapeHtml4(userInput);

    response.setContentType("text/html");
    response.getWriter().println("You entered: " + escapedUserInput);
  }
}

input form

Because the servlet escapes the data, the HTML is rendered as text in the output:

html output

See the server libraries tutorial and the sanitizing user input tutorial for more information.



Comments and Questions

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!