Servlets · Lesson 10
Handling Forms and File Uploads
Processing Form Data
HTML forms send named fields that a servlet reads with getParameter. Validation belongs at the server boundary because browsers can be bypassed and clients can send unexpected values. A valid form flow should report errors clearly and avoid partially applying changes.
Reading Fields Safely
Read each parameter deliberately, normalize values where appropriate, and validate required fields before calling a service layer. The servlet should not embed database or file-storage logic.
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/profile")
public class ProfileFormServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String displayName = request.getParameter("displayName");
String emailAddress = request.getParameter("email");
if (displayName == null || displayName.isBlank() || emailAddress == null || !emailAddress.contains("@")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "A valid name and email are required");
return;
}
response.getWriter().println("Profile accepted for " + displayName);
}
}
File Upload Concepts
| Concern | Good approach | Why it matters |
|---|---|---|
| Encoding | multipart/form-data | Sends binary content correctly |
| Size | Container and application limits | Prevents resource exhaustion |
| Name | Generate a server-side name | Avoids path and collision problems |
| Type | Validate content and extension | Reduces malicious uploads |
| Storage | Use controlled storage outside web root | Prevents accidental execution |
Common Mistake and Practices
Common Mistake: Trusting an uploaded filename or MIME type and writing it directly to a public directory. Attackers can submit path traversal strings or files that should never be served as executable content.
- Validate every field on the server.
- Limit request size and upload count.
- Generate storage names rather than trusting client names.
- Scan or inspect uploaded content when the domain requires it.
- Return validation errors without exposing internal paths.
Real-World Use Case
A learning platform accepts a profile image and display name in one form. The servlet validates both fields, stores the image under a generated identifier, and saves only the safe identifier with the learner profile.
Quiz Check