Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 119 ยท Servlets and JSP

Handling Requests, Forms and Redirects

Read servlet request parameters and forms, pass data with request attributes, choose forward or redirect, send the right status codes and handle file uploads safely.

A servlet's job is to turn an HTTP request into a response. In the previous lesson you wrote doGet and doPost methods that printed fixed text. Real pages need input: a search term in the URL, a sign-up form, an uploaded profile picture. They also need to decide what happens next: show a page, send the browser somewhere else, or report an error with the right status code.

This lesson covers the request side in depth. You will read parameters the way a servlet container does, handle a form with validation, learn when to forward and when to redirect, use the Post/Redirect/Get pattern, and accept file uploads without opening a security hole. Servlet code can't run in this sandbox, so each servlet is shown read-only next to a runnable program that does the same thing with the JDK's built-in HttpServer and HttpClient. If servlets are new to you, start with Servlets.

Where request data comes from

An HTTP request carries data in several places, and the HttpServletRequest interface has a method for each:

Data Example How to read it
Query string /search?q=java&page=2 getParameter("q"), getQueryString()
Form body (application/x-www-form-urlencoded) name=Ana&age=31 getParameter("name")
Path after the servlet mapping /books/42 with mapping /books/* getPathInfo() returns "/42"
Headers Accept-Language: de getHeader("Accept-Language"), getLocale()
Cookies Cookie: theme=dark getCookies()
Raw body (JSON, XML) {"title":"Dune"} getReader() or getInputStream()
Multipart body (file uploads) multipart/form-data; boundary=... getPart("file"), getParts()

The parameter methods merge the first two rows: the container decodes the query string and, for a POST with a URL-encoded form body, the body too, and gives you one map. That is why the same getParameter("q") works for both <form method="get"> and <form method="post">.

Java
String q = request.getParameter("q");              // first value, or null if missing
String[] tags = request.getParameterValues("tag");   // all values, or null if missing
Map<String, String[]> all = request.getParameterMap(); // read-only map of everything
Enumeration<String> names = request.getParameterNames();

Four rules catch many beginners:

  • A missing parameter is null; an empty field is "". A text box the user left blank is still submitted with an empty value. A checkbox that is not ticked is not submitted at all.
  • getParameter returns only the first value. Checkbox groups and multi-select lists send the same name several times, so use getParameterValues.
  • Everything is a String. Converting "31" to an int is your job, and Integer.parseInt throws on "thirty" or "". Validate before you convert.
  • Set the character encoding before the first read. Call request.setCharacterEncoding("UTF-8") before any getParameter call, or configure <request-character-encoding>UTF-8</request-character-encoding> in web.xml (Servlet 4.0 and later). Otherwise some containers decode the body as ISO-8859-1 and "Sรฃo Paulo" turns into garbage.

Here is what a container does when it builds that parameter map. The program decodes a query string with URLDecoder, keeps every value of repeated names, and then shows the encoding mistake from the last rule.

Java Decoding parameters like a servlet container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that + became a space in Ana Lima: in form encoding a plus sign means space, and a real plus is sent as %2B. The last line shows the classic encoding bug. The two UTF-8 bytes of รฃ were read as two separate ISO-8859-1 characters, so the city prints as Sรƒยฃo Paulo.

Handling a form

A typical form servlet does three things. doGet shows the empty form. doPost reads and validates the input. If the input is invalid, it shows the form again with the user's values and error messages; if it is valid, it saves the data and redirects.

Java
@WebServlet("/signup")
public class SignupServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/views/signup.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String email = trimToEmpty(request.getParameter("email"));
        String ageText = trimToEmpty(request.getParameter("age"));

        Map<String, String> errors = new LinkedHashMap<>();
        if (!email.matches("[^@\\s]+@[^@\\s]+\\.[^@\\s]+")) {
            errors.put("email", "Enter a valid email address.");
        }
        Integer age = null;
        try {
            age = Integer.valueOf(ageText);
            if (age < 13 || age > 120) errors.put("age", "Age must be between 13 and 120.");
        } catch (NumberFormatException e) {
            errors.put("age", "Age must be a whole number.");
        }

        if (!errors.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);     // 400
            request.setAttribute("errors", errors);
            request.setAttribute("email", email);                       // re-fill the form
            request.setAttribute("age", ageText);
            request.getRequestDispatcher("/WEB-INF/views/signup.jsp").forward(request, response);
            return;
        }

        userService.register(email, age);
        response.sendRedirect(request.getContextPath() + "/welcome");   // Post/Redirect/Get
    }

    private static String trimToEmpty(String s) {
        return s == null ? "" : s.strip();
    }
}

Two habits in this code are worth copying. The validation never trusts the browser: HTML attributes such as required or type="email" improve the experience, but anyone can send a request without a browser. And the user's values are put back into the form so they don't have to retype everything; the view must escape them when it prints them, which the JSTL lesson shows with <c:out>.

Request attributes: data for the next step

Parameters come from the client and are read-only strings. Attributes are objects your code attaches to the request with setAttribute(name, value) and reads with getAttribute(name). They live exactly as long as the request, and their main use is handing data from a servlet (the controller) to the JSP or other component that renders the page.

There are four places to store attributes, from shortest to longest life:

Scope Object Lives until Typical use
Page PageContext (JSP only) the JSP finishes temporary variables inside one view
Request HttpServletRequest the response is sent the model for one page: a list of books, form errors
Session HttpSession logout or timeout the logged-in user, a shopping cart
Application ServletContext the app is undeployed shared, read-mostly data: configuration, caches

Use the shortest scope that works. Data put in the session by mistake stays in memory for every user for half an hour, and data in the application scope is shared by all threads at once. Sessions get their own lesson: Sessions and Cookies.

Forward vs redirect

When a servlet has done its work, it usually passes control on in one of two ways:

  • Forward (request.getRequestDispatcher("/WEB-INF/views/list.jsp").forward(request, response)) happens inside the server. The container hands the same request and response objects to another resource. The browser never knows; its address bar still shows the original URL. Request attributes survive, because it is still one request.
  • Redirect (response.sendRedirect("/books")) tells the browser to go somewhere else. The server answers with a 3xx status and a Location header, and the browser sends a brand-new request. The URL changes, request attributes are gone, and it costs one extra round trip.
Forward Redirect
Who moves the server, internally the browser, with a new request
Address bar unchanged shows the new URL
Request attributes kept lost
Target only resources in the same web app any URL, even another site
Typical use servlet โ†’ JSP view after a successful POST; moved pages; login required

A third option, include, inserts another resource's output into the current response and then continues; it is used for shared fragments such as headers.

Two rules prevent IllegalStateException. You can't forward or redirect after the response is committed (once the first bytes have been sent to the client), so don't write output before deciding where to go. And after calling forward or sendRedirect, return from the method: the call does not stop your code, and anything you do afterwards is either ignored or an error.

Post/Redirect/Get

If a servlet answers a successful POST by rendering a page directly, the browser's last request is that POST. Pressing reload then asks "Resubmit the form?", and a careless user places the order twice. The fix is Post/Redirect/Get (PRG): handle the POST, then redirect to a GET page that shows the result. Reloading that page only repeats the harmless GET.

The redirect status matters:

Status Meaning Method of the follow-up request
301 Moved Permanently the resource has a new permanent URL browsers change POST to GET
302 Found temporary move (what sendRedirect sends) browsers change POST to GET (historical behavior)
303 See Other "see the result over there" always GET: made for PRG
307 Temporary Redirect temporary move method and body are kept
308 Permanent Redirect permanent move method and body are kept

sendRedirect sends 302, which works for PRG in every browser. To send 303 explicitly, set the status and header yourself: response.setStatus(303); response.setHeader("Location", url);. Servlet 6.1 (Jakarta EE 11) also added sendRedirect overloads that take a status code.

The next program is a tiny guestbook that follows PRG. GET /guestbook lists messages, POST /guestbook validates and stores a message and answers 303, and other methods get 405 Method Not Allowed. The client is configured to follow redirects like a browser, and it prints each hop.

Java A guestbook with Post/Redirect/Get

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first block shows PRG at work: the POST got a 303 with Location: /guestbook, and the client followed it with a GET that returned the updated list. A blank message (three encoded spaces) never reaches the list; it gets 400 and no redirect, just like the servlet above re-renders the form. The DELETE gets 405 with an Allow header, which is exactly what HttpServlet does for you when you don't override doDelete.

Simulating forward and redirect

The difference between the two is easiest to see from the client. In the next program, /dashboard "forwards": it puts data into a per-request attribute map and calls the view code directly, all inside one exchange. /old-dashboard redirects to /dashboard. The client prints the final URL, the number of round trips and whether the view received the attribute.

Java Forward vs redirect from the client's point of view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The forward needed one round trip and the URL stayed /dashboard. The redirect needed two, the browser ended up on a different URL, and the attribute the first request prepared was lost; the second request rendered with whatever its own handler supplied. That is why you forward to views and redirect between actions.

Status codes and errors

Every response has a status code, and choosing the right one matters for browsers, search engines, caches and API clients. HttpServletResponse has constants for the common ones (SC_OK, SC_CREATED, SC_BAD_REQUEST, SC_NOT_FOUND, ...) and two ways to use them:

Java
response.setStatus(HttpServletResponse.SC_CREATED);                 // 201, you write the body
response.sendError(HttpServletResponse.SC_NOT_FOUND, "No book 42");  // 404, container's error page

setStatus only changes the code; you still write the response body. sendError hands the response to the container, which renders an error page and commits the response, so don't write anything afterwards. You can replace the container's default error pages in web.xml:

XML
<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/errors/not-found.jsp</location>
</error-page>
<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/WEB-INF/views/errors/server-error.jsp</location>
</error-page>

The second entry catches any exception that escapes a servlet, so users see a friendly page instead of a stack trace. A good rule of thumb: 400 for input the client must fix (or 422 if your API distinguishes well-formed but invalid data), 401 when the user is not logged in, 403 when they are logged in but not allowed, 404 for missing resources, 405 for wrong methods and 500 for bugs. The REST API Design lesson goes deeper for JSON APIs.

Uploading files

A form that uploads files must use method="post" and enctype="multipart/form-data". The body is then split into parts, one per field, separated by a boundary string. Since Servlet 3.0 the container parses it for you when the servlet carries @MultipartConfig:

HTML
<form action="/avatar" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" accept="image/png, image/jpeg">
  <button>Upload</button>
</form>
Java
@WebServlet("/avatar")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024,        // keep parts up to 1 MB in memory
    maxFileSize = 5 * 1024 * 1024,          // reject single files over 5 MB
    maxRequestSize = 6 * 1024 * 1024)       // reject whole requests over 6 MB
public class AvatarServlet extends HttpServlet {

    private static final Path UPLOADS = Path.of("/var/app/uploads");

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part part = request.getPart("avatar");
        if (part == null || part.getSize() == 0) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Choose a file");
            return;
        }
        String extension = switch (part.getContentType()) {
            case "image/png" -> ".png";
            case "image/jpeg" -> ".jpg";
            default -> null;
        };
        if (extension == null) {
            response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);   // 415
            return;
        }
        Path target = UPLOADS.resolve(UUID.randomUUID() + extension);   // our name, not theirs
        try (InputStream in = part.getInputStream()) {
            Files.copy(in, target);
        }
        response.sendRedirect(request.getContextPath() + "/profile");
    }
}

When a file exceeds the limits, getPart throws an IllegalStateException, which you can map to a 413 Content Too Large error page. Ordinary text fields in a multipart form are still available through getParameter.

Everything about an upload is controlled by the client: the file name, the content type and the bytes. Never use getSubmittedFileName() as the stored path, never store uploads inside the web app folder where they could be served or executed, and check the content itself (for example the first bytes of the file) when the type matters.

Here is why the file name is dangerous, and a safe way to handle it. The program sanitizes several submitted names, checks that the result stays inside the upload folder and sniffs the first bytes of the content.

Java Making uploaded file names safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The naive version lets ../../../etc/cron.d/job escape the upload folder entirely, which could let an attacker plant a scheduled job on the server. The Windows path keeps its backslashes on a Linux server, because \ is an ordinary character there, so the safe version strips both separators itself. shell.jsp is rejected outright: an uploaded .jsp inside the web app would be compiled and run by the server. And content sniffing shows that a file named invoice.pdf can contain anything at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A form has a text box nickname that the user left blank and an unticked checkbox terms. What do getParameter("nickname") and getParameter("terms") return?

    An empty text box is still submitted, with an empty value. An unticked checkbox is not submitted at all, so its parameter is null.
  2. 2. A servlet sets a request attribute and then calls response.sendRedirect("/report"). Can the servlet for /report read the attribute?

    Request attributes live for one request. A redirect ends that request and the browser starts a new one. Use forward, the session or a query parameter instead.
  3. 3. Why should a successful form POST end with a redirect to a GET page?

    This is the Post/Redirect/Get pattern. After the redirect, the browser's last request is a harmless GET, so reload and bookmarks work as users expect.
  4. 4. Which redirect status keeps the method and body of a POST when the browser follows it?

    307 and 308 require the client to repeat the same method with the same body. 303 always switches to GET, and browsers switch 301 and 302 to GET for historical reasons.
  5. 5. Why store an upload under a generated name such as a UUID instead of getSubmittedFileName()?

    The submitted name is untrusted input. It can escape the upload folder, overwrite files or carry an extension like .jsp that the server would execute.

Summary

  • getParameter returns the first value or null; getParameterValues returns all values. Query strings and URL-encoded form bodies end up in the same parameter map.
  • Missing means null, blank means "", and every parameter is a String you must validate and convert. Set the request encoding to UTF-8 before reading.
  • Attributes carry objects between components. Request scope is the default home for a page's model; use session and application scope sparingly.
  • Forward stays inside the server with the same request; redirect sends the browser to a new URL with a new request.
  • Use Post/Redirect/Get after successful form submissions; 303 See Other is the precise status, 302 (from sendRedirect) works too.
  • Use setStatus when you write the body and sendError to let the container render an error page; configure <error-page> for friendly errors.
  • File uploads need enctype="multipart/form-data" and @MultipartConfig with size limits. Treat the file name, type and content as hostile.

Next: Sessions and Cookies shows how a server remembers a user from one request to the next.