Servlet Request Parameters, and Forward vs Redirect
Read ?name=Emma with getParameter, then hand a request on two ways: a forward keeps one request and its attributes, a redirect makes the browser ask again and the attribute is gone.
What you will learn
- Read a value from the query string with getParameter, and know when it is null
- Pass data to a JSP with a request attribute and a forward
- Explain why a redirect loses request attributes and changes the address bar
- Choose between forward and sendRedirect
Before you start
- The Servlet Request Lifecycle
- JSP expressions
Two everyday jobs in a servlet: read a value the browser sent in the URL, and hand the request on to someone else. Handing on comes in two flavours, forward and redirect, which look alike and behave very differently.
Read a value from the URL
Everything after the ? in a URL is a list of parameters, as key=value pairs joined with &. In /greet?name=Emma the key is name and the value is Emma.
package org.studyeasy.web;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
// /greet?name=Emma - the part after ? carries the parameters
@WebServlet("/greet")
public class GreetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// read ?name=... from the URL; null when it is not there
String name = req.getParameter("name");
resp.setContentType("text/html");
resp.getWriter().println("<h1>Hello, " + name + "</h1>");
}
}
/request-dispatch/greet?name=Emma -> Hello, Emma
/request-dispatch/greet -> Hello, null
req.getParameter("name") always returns a String. If the parameter isn't there, you don't get an error, you get null, and the page cheerfully says "Hello, null". With several pairs, say name=Jake plus a name2 pair, getParameter("name") only picks the key you ask for (Jake), and name2 is ignored.
One round trip or two
forward: the same request
package org.studyeasy.web;
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("/forward")
public class ForwardServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// an attribute lives as long as this one request
req.setAttribute("message", "Order 1042 is ready");
System.out.println("ForwardServlet: forward to /result.jsp");
// same request, handed to the JSP inside the server
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
}
Both servlets end up on this one JSP:
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<h1>Order status</h1>
<%-- request: the request this page is answering --%>
<p>Message: <%= request.getAttribute("message") %></p>
</body>
</html>
Open /forward. The address bar keeps /forward, and the page shows:
Order status
Message: Order 1042 is ready
The servlet's own line shows up in the server log: ForwardServlet: forward to /result.jsp.
setAttribute puts a value on this request. An attribute lives exactly as long as the request. getRequestDispatcher("/result.jsp").forward(req, resp) passes the same request and response to the JSP inside the server, so request.getAttribute("message") finds it.
sendRedirect: a new request
package org.studyeasy.web;
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("/redirect")
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
req.setAttribute("message", "Order 1042 is ready");
System.out.println("RedirectServlet: redirect to /result.jsp");
// tell the BROWSER to ask for another URL: a second request.
// getContextPath() is the app's part of the URL
resp.sendRedirect(req.getContextPath() + "/result.jsp");
}
}
Open /redirect. The servlet answers 302 Found with Location: .../request-dispatch/result.jsp, the address bar changes, and the page shows:
Order status
Message: null
The same attribute was set, but the first request ended with that 302 and the attribute went with it. The browser's second request is brand new and carries nothing. getContextPath() is your app's part of the URL (/request-dispatch here). A redirect can point anywhere, even another website.
forward or sendRedirect?
| forward | sendRedirect | |
|---|---|---|
| Called on | the request dispatcher | the response |
| Goes to | a page inside your app | any URL |
| Requests | one | two |
| Address bar | stays the same | changes |
| Request attributes | kept | gone |
Use forward to show a page with your data. Use redirect to send the user to a new URL. Most of the time you'll see forward: a servlet processes some data and a JSP displays it. That split is the start of MVC with servlets and JSP.
Common mistakes
- Wrong case in a name. Parameter and attribute names are case-sensitive:
getParameter("Name")on?name=Emmagives "Hello, null", andgetAttribute("Message")gives "Message: null" even after a forward. - A wrong path in the dispatcher,
"/results.jsp". The browser gets HTTP 404 for/request-dispatch/forward. - A wrong path in a redirect. The redirect still happens, and the browser's second request gets the 404.
- Setting an attribute and then redirecting, and expecting the next page to see it. Use a forward, or put the value in the URL or the session.
Quick recap
req.getParameter("key")reads the query string; a missing key givesnull.req.setAttributeplusforwardhands data to a JSP within one request.resp.sendRedirect(url)answers 302 and the browser makes a fresh request.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
A JSP looks like HTML with a little Java, yet Tomcat runs it as a servlet. See what a servlet container does for each request, what the generated hello_jsp.java looks like, what a .war holds, and Tomcat vs TomEE.
Set Up Tomcat 11 and a Maven Web Project in IntelliJ IDEA
Set JAVA_HOME, install Tomcat 11 on a free port, create a Jakarta EE web application with Maven in IntelliJ IDEA, read its folders and pom.xml, and run it on Tomcat.
The Servlet Request Lifecycle: @WebServlet, web.xml, init, doGet and destroy
A servlet is a Java class that answers a URL. Follow one request through Tomcat, map servlets with @WebServlet and web.xml, build a page from a list, and watch init, doGet and destroy run.
Run a Java Web App in Docker: Tomcat 11 With One Compose Command
Run a servlet project without installing Tomcat: one docker compose command builds the WAR with Maven on Java 25, starts Tomcat 11 in a container, and serves the app on localhost:8090.
