This example uses an HTML form to create a POST request containing the user’s name.
index.html contains an HTML form:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter some input:</h1>
<form action="/user-input-unsanitized/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 outputting the user’s input directly to 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;
@WebServlet("/form")
public class FormServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String data = request.getParameter("data");
response.setContentType("text/html");
response.getWriter().println("You entered: " + data);
}
}
Because the servlet does not sanitize the data, the HTML is rendered in the output:
See the server libraries tutorial and the sanitizing user input tutorial for more information about why this is bad, and what to do about it.
See what happens when you don't sanitize user input.
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!
Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!