Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In a JSP scriptlet, call response.sendRedirect(...) and then return; to stop the JSP’s remaining Java code from running. A redirect prepares an HTTP response for the client; it does not exit the current JSP, servlet method, or filter.

Why code after a JSP redirect still runs

sendRedirect sets up a response that normally tells the client to go to another URL. The Jakarta Servlet 6.1 API documents the one-argument method as sending a 302 Found response, clearing the response buffer, and committing the response. The browser normally follows the redirect by making a new request. None of that is a Java control-flow statement, so the current handler continues unless it exits explicitly. See the Jakarta Servlet 6.1 HttpServletResponse API.

A JSP’s body is executed through its generated _jspService(...) method. Returning from a scriptlet exits that method, as reflected in the Jakarta Server Pages JspPage API.

Incorrect: redirect without exiting

<%
if (session.getAttribute("user") == null) {
    response.sendRedirect("login.jsp");
}

out.println("This code still executes");
%>

The redirect branch does not skip the print statement or any later Java logic. That can mean unwanted output, database work, or other side effects even though the client receives a redirect response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Correct: redirect and return

<%
if (session.getAttribute("user") == null) {
    String loginUrl = request.getContextPath() + "/login";
    response.sendRedirect(response.encodeRedirectURL(loginUrl));
    return;
}
%>

<h1>Authenticated content</h1>

Put access checks before page markup or other output. The JSP scriptlet is valid, but request-control logic is usually easier to maintain in a filter or controller, leaving the JSP to render the view.

Use the right pattern for a JSP, servlet, or filter

JSP scriptlet

Use return; after the redirect to exit the JSP service method:

<%
if (!isAuthorized) {
    response.sendRedirect(request.getContextPath() + "/access-denied");
    return;
}
%>

Servlet

In a servlet, return; exits the current handler method, such as doGet or doPost:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
if (!isAuthenticated(request)) {
    response.sendRedirect(request.getContextPath() + "/login");
    return;
}

request.getRequestDispatcher("/WEB-INF/views/home.jsp")
       .forward(request, response);

Filter

A filter must not continue the chain on the redirect branch. Calling chain.doFilter would allow downstream filters or the target resource to run:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if (!isAllowed(httpRequest)) {
    httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
    return;
}

chain.doFilter(request, response);

Returning exits only the current method or JSP service method. It does not undo work already completed, roll back a transaction, stop other threads, or cancel asynchronous tasks already started. Make authorization decisions before launching work that must not happen for an unauthorised request.

Redirect or forward: which should you use?

Question sendRedirect forward
Where does dispatch happen? The client receives redirect metadata and normally makes a new request. The server dispatches internally within the current request.
Does the browser URL normally change? Yes, when a browser follows the redirect successfully. No; it normally remains the original URL.
Which request reaches the target? A new request. Original request attributes are not carried automatically. The same request, so request attributes can be used by the target.
Can the destination be external? Yes, if the target is valid and trusted. Normally the target is a resource in the same web application.
Typical use Login navigation, external destinations, or POST/Redirect/GET. Dispatching from a controller or servlet to a server-rendered view.

The Servlet API’s RequestDispatcher.forward documentation requires the response to be uncommitted; buffered output is cleared before the forward. Return after forwarding if the calling method has no more work to do:

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
request.setAttribute("message", "Welcome");
request.getRequestDispatcher("/WEB-INF/views/home.jsp")
       .forward(request, response);
return;

In a JSP, <jsp:forward page="/login.jsp" /> performs a server-side forward, not a browser redirect. The Jakarta Server Pages specification says the action effectively terminates execution of the current page. The programmatic equivalent is pageContext.forward(...); after a successful forward, return rather than modifying the response, as advised by the Jakarta PageContext.forward API.

Avoid redirecting after output has been committed

A redirect must be set before the response is committed. This is unsafe because HTML may already have been flushed:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<html>
<body>
    Existing output
<%
response.sendRedirect("login.jsp");
%>
</body>
</html>

JSP output is commonly buffered, but that does not make redirecting after output reliable. The buffer can be flushed explicitly, when full, or through page and container behavior. The JSP specification explains that response headers can be changed only until output is flushed. Prefer making the navigation decision before producing page output:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
<%
if (needsLogin) {
    response.sendRedirect(request.getContextPath() + "/login");
    return;
}
%>

<!doctype html>
<html>
...

If you encounter an “already committed” error, response.isCommitted() can help diagnose whether the response is too late for a redirect. It is not a substitute for correct control flow: if the response is committed, a normal redirect generally cannot be sent on it.

  • Look for earlier HTML output, out.flush(), or response.flushBuffer().
  • Check JSP buffer settings such as buffer="none" and whether the buffer could have filled.
  • Check whether an included page or another component wrote or committed the response.
  • Keep the redirect branch before rendering begins.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Build an application URL deliberately

For an internal redirect, a context-aware target avoids assuming that the application is deployed at the server root:

String loginUrl = request.getContextPath() + "/login";
response.sendRedirect(response.encodeRedirectURL(loginUrl));
return;

encodeRedirectURL supports session tracking when URL rewriting is needed. A leading slash in a redirect path is interpreted relative to the servlet container root, while a path without one is relative to the current request URI; the exact outcome depends on the request and deployment. Tomcat’s HttpServletResponse API documentation describes these path rules. In practice:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
  • "login.jsp" is relative to the current request URI.
  • "/login.jsp" starts at the container root and may omit the application context.
  • request.getContextPath() + "/login" explicitly targets the application context.

Do not pass an untrusted query parameter straight to sendRedirect. A redirect to an attacker-chosen destination can create an open redirect. Validate destinations against an allowlist or construct them from known internal paths.

Use redirects for POST/Redirect/GET

After successfully processing a form POST, redirect to a page that can be retrieved with GET:

if ("POST".equalsIgnoreCase(request.getMethod())) {
    long id = saveRecord(request);
    response.sendRedirect(request.getContextPath() + "/records/" + id);
    return;
}

When the browser follows this redirect, the next request is normally a GET, so refreshing the result page avoids the usual resubmission of the original POST. The write must happen before the redirect, and code after the redirect still needs to be excluded with return.

The classic one-argument sendRedirect(String) is documented as using 302 Found in the Jakarta Servlet 6.1 API. HTTP also defines other redirect statuses: 303 See Other is commonly used when a POST should be followed with GET, while 307 Temporary Redirect and 308 Permanent Redirect preserve the method. Whether an explicit-status redirect overload is available depends on the Servlet API and container version; older javax.servlet applications should verify their API before using one. Do not assume newer jakarta.servlet examples compile unchanged in older applications.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Debug a redirect that seems to continue

  1. Confirm the redirect condition is reached, and add return; immediately afterward.
  2. If the code is in a filter, confirm the redirect branch does not call chain.doFilter(...).
  3. Search for output or flushes before the redirect, then check whether the response is committed.
  4. Inspect the browser’s Network panel: look for a redirect status and a Location header, then check what URL is requested next. Non-browser clients do not necessarily follow redirects automatically.
  5. Verify the target includes the application context where needed, and check that the target is not redirecting back to the original URL.
  6. Log the original request URI, redirect target, access decision, and response status when diagnosing a loop. Do not log credentials, session tokens, or sensitive query parameters.

If a redirect appears to happen but protected content is still produced, first check for a missing return, a filter-chain call, earlier output, or continued processing in an include or wrapper. A framework response wrapper may change buffering details, but it does not make it safe to write after a redirect.

Put navigation and access checks in the request-handling layer

JSPs can issue redirects, but authentication, authorization, validation, and data changes usually belong in a filter, servlet, or framework controller. A maintainable flow checks access before rendering, redirects when needed, and forwards an authorised request to a JSP view. A redirect issued from an include has no effect under the Servlet API, another reason not to put navigation decisions in reusable JSP fragments. See the Servlet API redirect behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.