Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

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

ConcernGood approachWhy it matters
Encodingmultipart/form-dataSends binary content correctly
SizeContainer and application limitsPrevents resource exhaustion
NameGenerate a server-side nameAvoids path and collision problems
TypeValidate content and extensionReduces malicious uploads
StorageUse controlled storage outside web rootPrevents 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

Quick Knowledge Test

Loading quiz questions...